Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract property of array in nested array

I have an array, which contains array of objects. I need to extract the property value "id" of items that have objects.

Example of array:

let myArray = [
    [ {id: "1"}, {id: "2"} ],
    [],
    [],
    [ {id: "3"} ]
]

How can I extract and create an array like this:

["1", "2", "3"]

I tried this:

tagIds = myArray.map(id =>{id})
like image 271
AlexFF1 Avatar asked Dec 03 '22 20:12

AlexFF1


2 Answers

You can use reduce to flatten the array and use map to loop thru the array and return the id.

let myArray = [
  [{id: "1"}, {id: "2"}],
  [],
  [],
  [{id: "3"}],
];

let result = myArray.reduce((c, v) => c.concat(v), []).map(o => o.id);

console.log(result);
like image 71
Eddie Avatar answered Jan 02 '23 12:01

Eddie


Another way with simple nested loops:

let myArray = [
    [ {id: "1"}, {id: "2"} ],
    [],
    [],
    [ {id: "3"} ]
]   

//----------------------------------

let newArray=[];    
for (let i=0;i<myArray.length;i++){
    for (let j=0;j<myArray[i].length;j++){
    newArray.push(myArray[i][j].id);
  }
}
console.log(newArray); //outputs ['1','2','3']
like image 42
treecon Avatar answered Jan 02 '23 11:01

treecon