从 Keys 数组创建 Javascript 对象
Create Javascript object from Keys arrays
我正在为无法实现的操作而苦苦挣扎,我有许多这样的数组:
['key1', 'key2', 'key3']
['key1', 'key2', 'key4']
['key1', 'key5']
这个数组中的每一个都有对应的值:
value1
value2
value3
我想从每个数组创建一个空对象,该对象具有基于数组中键位置的层次结构,例如:
['key1', 'key2', 'key3'] => { key1: { key2: { key3: value1 } } }
最后,合并这些对象并构建一个如下所示的对象:
var object = {
key1: {
key2: {
key3: value1,
key4: value2
},
key5: value3
}
}
我尝试了一些方法,但它们需要三个 for 循环迭代,我认为有更好的方法可以做到这一点,当然最后的合并是最简单的部分,我可以使用 jQuery merge 这样做,但我真的很难从每个数组创建单个对象。
非常感谢,如果您需要更多信息,请告诉我。
干杯
您可以使用 Array#reduce
,因为此 returns 是您需要的对象,无需在外部保留引用。
function set(object, path, value) {
var last = path.pop();
path.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var a = {};
set(a, ['key1', 'key2', 'key3'], 'value1');
set(a, ['key1', 'key2', 'key4'], 'value2');
set(a, ['key1', 'key5'], 'value3');
console.log(a);
function create(arr, value, o = {}) {
a = o;
// loop trough the object
for (i = 0; i < arr.length; i++) {
// add a new object with the name of an array object
a[arr[i]] = {};
// important step: move the pointer `a` deeper into the object...
a = a[arr[i]];
}
// set the last object's value to the passed value
a.value = value;
return o;
}
这样使用:
var object = create(["a", "b", "c"], true);
object2 = create(["d", "e", "f"], true, object);
我正在为无法实现的操作而苦苦挣扎,我有许多这样的数组:
['key1', 'key2', 'key3']
['key1', 'key2', 'key4']
['key1', 'key5']
这个数组中的每一个都有对应的值:
value1
value2
value3
我想从每个数组创建一个空对象,该对象具有基于数组中键位置的层次结构,例如:
['key1', 'key2', 'key3'] => { key1: { key2: { key3: value1 } } }
最后,合并这些对象并构建一个如下所示的对象:
var object = {
key1: {
key2: {
key3: value1,
key4: value2
},
key5: value3
}
}
我尝试了一些方法,但它们需要三个 for 循环迭代,我认为有更好的方法可以做到这一点,当然最后的合并是最简单的部分,我可以使用 jQuery merge 这样做,但我真的很难从每个数组创建单个对象。
非常感谢,如果您需要更多信息,请告诉我。
干杯
您可以使用 Array#reduce
,因为此 returns 是您需要的对象,无需在外部保留引用。
function set(object, path, value) {
var last = path.pop();
path.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var a = {};
set(a, ['key1', 'key2', 'key3'], 'value1');
set(a, ['key1', 'key2', 'key4'], 'value2');
set(a, ['key1', 'key5'], 'value3');
console.log(a);
function create(arr, value, o = {}) {
a = o;
// loop trough the object
for (i = 0; i < arr.length; i++) {
// add a new object with the name of an array object
a[arr[i]] = {};
// important step: move the pointer `a` deeper into the object...
a = a[arr[i]];
}
// set the last object's value to the passed value
a.value = value;
return o;
}
这样使用:
var object = create(["a", "b", "c"], true);
object2 = create(["d", "e", "f"], true, object);