[英]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.
我需要提取具有对象的项目的属性值“id”。
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})
You can use reduce
to flatten the array and use map
to loop thru the array and return the id.您可以使用
reduce
来展平数组并使用map
循环遍历数组并返回 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);
You can use .concat()
to create array of single objects and then .map()
to extract ids:您可以使用
.concat()
创建单个对象的数组,然后使用.map()
提取 id:
let myArray = [ [{id: "1"}, {id: "2"}], [], [], [{id:"3"}] ]; let result = [].concat(...myArray).map(({ id }) => id); console.log(result);
Docs:文档:
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']
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)
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]
. extractIds
的返回extractIds
[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).请注意,如果没有递归部分,您最终会得到这样的结果:
[1, 2, [3, {id: 4}, [{id: 5}]]]
(不完全是这样,但只是一个例子) .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.