gpt4 book ai didi

javascript - 将嵌套对象的每个对象的索引设置为属性

转载 作者:行者123 更新时间:2023-11-29 10:02:53 24 4
gpt4 key购买 nike

早上好!

有谁知道如何将嵌套对象的每个对象的索引插入到属性中?

是这样的:

const myObj = 
{
"@type": "someType",
A: [
{
"@type": "someType0",
order: "DESC",
myIndex: 0
},
{
"@type": "someType1",
order: "DESC",
myIndex: 1
},
{
"@type": "someType2",
order: "DESC",
myIndex: 2
}
],
B: [],
};

最佳答案

您可以使用递归方法并为所有数组添加一个索引。

function setIndex(object) {
Object.values(object).forEach(v => {
if (Array.isArray(v)) {
v.forEach((o, i) => {
o.index = i;
setIndex(o);
});
}
});
}

const object = { "@type": "someType", A: [{ "@type": "someType0", order: "DESC" }, { "@type": "someType1", order: "DESC" }, { "@type": "someType2", order: "DESC" }], B: [] };

setIndex(object);

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将嵌套对象的每个对象的索引设置为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51634023/

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