Reputation: 23
I have an array of objects in TypeScript(Angular), and I want only names from this array if details array is not empty
[
{name: "Joe", detail: []},
{name: "Kevin", detail: [{salary: 2400}] },
{name: "Peter", detail: [{salary: 2100}]}
]
I want this result Kevin,Peter in one variable
Currently I have done this
[
{name: "Joe", detail: []},
{name: "Kevin", detail: [{salary: 2400}] },
{name: "Peter", detail: [{salary: 2100}]}
].map(function(elem){
return elem.name;}).join(",")
Can anyone help me to do this in Typescript or JavaScript?
Upvotes: 0
Views: 63
Reputation: 14208
I do not want Joe in the result because
Joe's detail
is empty. I only wantkevin,Peter
You can use .reduce
combines with destructure object
like below to resolve it.
var data = [
{name: "Joe", detail: []},
{name: "Kevin", detail: [{salary: 2400}] },
{name: "Peter", detail: [{salary: 2100}]}
];
var result = data.reduce((acc, {name, detail}) => {
if(detail.length > 0) acc.push(name) // condition to add name into result
return acc;
}, []);
console.log(result.join(","));
Upvotes: 1
Reputation: 25408
const array = [
{ name: "Joe", detail: [] },
{ name: "Kevin", detail: [{ salary: 2400 }] },
{ name: "Peter", detail: [{ salary: 2100 }] },
];
const filteredArray = array.filter((obj) => {
return obj.detail.length > 0;
});
const result = filteredArray.map((obj) => obj.name).join(", ");
console.log(result);
Upvotes: 1