AlexFF1
AlexFF1

Reputation: 1283

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})

Upvotes: 5

Views: 7858

Answers (5)

fruitloaf
fruitloaf

Reputation: 2892

Here is my solution:

let a = myArray.flat(100) // you can put (3) or (10) in here, the higher the flatter the array

let b = a.map(

function(value){
return parseInt(value.id)
}
)

console.log(b)

Upvotes: 1

Mauricio Soares
Mauricio Soares

Reputation: 3640

You can also write a recursive function to make this work with any number of arrays, for example:

function extractIds(arr) {
    return arr.reduce((a, item) => {
        if (Array.isArray(item)) {
            return [
                ...a,
                ...extractIds(item)
            ];
        }

        return [
            ...a,
            item.id
        ];
    }, [])
}

extractIds([{id: 1}, [{id: 2}], {id: 3}, [{id: 4}, [{id: 5}, [{id: 6}]]]])

the return of extractIds will be [1, 2, 3, 4, 5, 6].

Notice that without the recursive part you would end up with something like this: [1, 2, [3, {id: 4}, [{id: 5}]]] (Not exactly like this, but just as an example).

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39322

You can use .concat() to create array of single objects and then .map() to extract ids:

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

let result = [].concat(...myArray).map(({ id }) => id);

console.log(result);

Docs:

Upvotes: 2

treecon
treecon

Reputation: 2825

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']

Upvotes: 2

Eddie
Eddie

Reputation: 26844

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);

Upvotes: 13

Related Questions