我有一个数组。可以说是:const array = ["lvl1", "lvl2", "lvl3", "key"]我有一个价值。可以说是:const value = false我有一个对象。可以说是:const object = { lvl1: { dogs: "bark", lvl2: { cats: "meow", lvl3: { cows: "moo" key: true } } }}如何创建一个包含arrayand的函数value,然后更新该对象,以便key使用新的更新数组中的(数组中的最后一项)value?需要根据array.length - 1数组中的第一个字符串适当地嵌套它。例如,我们将其称为函数createObject。如果我使用array并value已在上面将其定义为:const newObject = createObject(array, value)然后,newObject应该等于:{ lvl1: { dogs: "bark", lvl2: { cats: "meow", lvl3: { cows: "moo" key: false } } }}这是另一个具有不同嵌套级别的示例:const updatedObject = createObject(["lvl1", "lvl2", "cats"], "stink")然后,updatedObject应该等于:{ lvl1: { dogs: "bark", lvl2: { cats: "stink", lvl3: { cows: "moo" key: true } } }}我已经走了这么远,但没有用:import object from "./object"const createObject = (array, value) => { let results = object; for (let i = 0; i < array.length; i++) { i === array.length - 1 ? (results = results[array[i]] = { ...results[array[i]], [array[i]]: value }) : (results = results[array[i]] = { ...results[array[i]], [results[array[i]]]: {} }); } return results;}我不想更改初始对象。我想返回一个新对象。而且我不会在对象上添加任何新的键/值对,而只会更改现有的键/值对。
2 回答
烙印99
TA贡献1829条经验 获得超13个赞
这有点通用,因为它不假定源是一个名为的全局变量object:
let array = ["lvl1", "lvl2", "lvl3", "key"];
let value = false;
let createObject = (keys, value) => {
let o, obj = o = {};
let lastKey = keys.pop();
keys.forEach(key => o = o[key] = o[key] || {});
o[lastKey] = value;
return obj;
};
let addToObject = (obj, keys, value) => {
let o, copy = o = JSON.parse(JSON.stringify(obj));
let lastKey = keys.pop();
keys.forEach(key => o = o[key] = o[key] || {});
o[lastKey] = value;
return copy;
};
let x = createObject(array, value);
let y = addToObject(x, ['lvl1'], 3);
let z = addToObject(y, ['a', 'b', 'c'], 4);
console.log(x);
console.log(y);
console.log(z);
添加回答
举报
0/150
提交
取消