我需要创建一个嵌套的选项层次结构。这些选项是数组上的键,其中多个子选项作为嵌套对象。
我需要从此对象生成嵌套层次结构。
从这样的对象开始:
const starterObject = {
id1: {
1: { value: "A" },
2: { value: "B" },
3: { value: "C" },
},
id2: {
1: { value: 10 },
2: { value: 20 },
},
};
我需要最终得到一个像这样的排列对象:
const permutations2 = {
1: [{ value: "A" }, { value: 10 }],
2: [{ value: "A" }, { value: 20 }],
3: [{ value: "B" }, { value: 10 }],
4: [{ value: "B" }, { value: 20 }],
5: [{ value: "C" }, { value: 10 }],
6: [{ value: "C" }, { value: 20 }],
};
我尝试过这样的事情:
const starterObject = {
id1: {
1: { value: "A" },
2: { value: "B" },
3: { value: "C" },
},
id2: {
1: { value: 10 },
2: { value: 20 },
},
};
const permutationMatrix = [];
Object.keys(starterObject["id1"]).forEach(key2 =>
Object.keys(starterObject["id2"]).forEach(key1 =>
permutationMatrix.push([
starterObject["id1"][key2],
starterObject["id2"][key1],
])
)
);
console.log(permutationMatrix)
但问题是按键是硬编码的。实际对象将有 1-5 个键 (id1 - id5) 和任意数量的嵌套对象。
我认为这需要递归,但我不确定如何从这里继续。
最佳答案
Reduce、条目和值可以提供帮助,并且无需递归。
const starterObject = {
id1: {
1: { value: "A" },
2: { value: "B" },
3: { value: "C" },
},
id2: {
1: { value: 10 },
2: { value: 20 },
},
id3: {
1: { value: 100 }
}
};
var entries = Object.entries(starterObject)
var out = entries.reduce((arr, group) => {
const itms = Object.values(group)[1]
const vals = Object.values(itms)
// if first time, set up the initial arrays with first set of data
if (!arr.length) {
return vals.map(v => [v])
}
// after first one, we will just loop over the arrays
// and start adding the next set of data to each one
return arr.reduce((updated, curr) => {
vals.forEach(val => {
// make copy so we are not adding data to the reference
const copy = curr.slice()
copy.push(val)
updated.push(copy)
})
return updated
}, [])
}, [])
console.log(JSON.stringify(out))
关于javascript - 生成 Javascript 对象键/值的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113779/