gpt4 book ai didi

javascript - 如何在javascript中迭代嵌套数组对象

转载 作者:行者123 更新时间:2023-11-29 18:43:16 26 4
gpt4 key购买 nike

我想知道如何在 Javascipt 中遍历嵌套的对象数组?我有一个名为 obj 的示例对象。我想根据条件 'in' 是 'string' 和 'out' 'number' 检索对象。

// tried got stuck
const output = [];
myList.forEach(entry => {
Object.keys(entry).forEach(key => {
const entity = entry[key][0];
if (entity.in === "string" && entity.out === "number") {
output.push(entity);
}
});
});
var obj = [{
"ston": [{
"id": "identity1",
"in": "string",
"out": "number",
"value": 10
},{
"id": "identity2",
"in": "string",
"out": "number",
"value": 10
}],
"nton": [{
"id": "identity1",
"in": "number",
"out": "number",
"value": 20
},{
"id": "identity2",
"in": "number",
"out": "number",
"value": 30
}]
}]

预期输出

   [{
"id": "identity1",
"in": "string",
"out": "number",
"value": 10
},{
"id": "identity2",
"in": "string",
"out": "number",
"value": 10
}]

最佳答案

您可以将该对象重建为嵌套数组,然后展平,最后过滤

var obj = [
{
"ston": [
{"id": "identity1", "in": "string", "out": "number", "value": 10},
{"id": "identity2", "in": "string", "out": "number", "value": 10}
],
"nton": [
{"id": "identity1", "in": "number", "out": "number", "value": 20},
{"id": "identity2", "in": "number", "out": "number", "value": 30}
]
}
];

const tmp = obj.map(e => Object.entries(e).map(([k, v]) => v)).flat(3)

const rs = tmp.filter(e => e.out==='number' && e.in ==='string')

console.log(rs)

关于javascript - 如何在javascript中迭代嵌套数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com