我想根据父键
推送子对象值示例代码:
let parent = {}
let newobj = {}
function setData(pid, cid, val) {
// let newobj = {}
newobj[cid] = val;
parent[pid] = newobj;
}
setData(1, 0, true)
setData(1, 1, false)
setData(0, 1, true)
console.log(parent)
预期输出为:
{
0: {1: true},
1: {0: true, 1: false}
}
答案 0 :(得分:1)
您需要重用父级的现有对象
let parent = {}
function setData(pid, cid, val) {
let newobj = parent[pid] || {};
newobj[cid] = val;
parent[pid] = newobj;
}
setData(1, 0, true)
setData(1, 1, false)
setData(0, 1, true)
console.log(parent)
或者,如果使用es6,您可以传播对象并一次性更新
let parent = {}
function setData(pid, cid, val) {
parent[pid] = {
...parent[pid],
[cid]: val
}
}
setData(1, 0, true)
setData(1, 1, false)
setData(0, 1, true)
console.log(parent)
(虽然每次都会创建一个新对象)