问题描述
我在将数组转换为键和值的对象时遇到麻烦。
目前,我有以下嵌套数组:
var array = [[id1,parent1,"name1","desc1"],[id2,"name2","desc2"],[id3,"name3","desc3"]];
数组长度是动态的。
对于我的代码,我需要对数组进行转换,使其成为键和值(由每个嵌套数组的第一个(id)和第三个(名称)值组成)的对象。
例如,上述数组的对象如下:
var obj = {id1: name1,id2: name2,id3: name3};
其中id值(id1,id2,id3)将是相应的整数值。
我很抱歉以前是否曾提出过类似的问题,但似乎找不到能够解决我问题的类似问题。
任何帮助或建议将不胜感激!
解决方法
您基本上想将原始数组转换成[key,value]
对数组。然后,您可以使用Object.fromEntries
函数将这些键/值转换为对象。所以,像这样:
const arr = [
["id1","parent1","name1","desc1"],["id2","parent2","name2","desc2"],["id3","parent3","name3","desc3"],];
const results = Object.fromEntries(arr.map(x => ([x[0],x[2]])))
console.log(results)
,
您可以使用简单的for循环来实现
var array = [
["id1","desc3"]
];
const obj = {}
for (const item of array) {
obj[item[0]] = item[2];
}
console.log(obj);
,
在使用Array.map
从数组中每个元素中提取第一和第三项之后,可以使用Object.fromEntries
将提取的键/值对数组转换为对象:
const [id1,id2,id3,parent1] = [1,2,3,4];
const array = [
[id1,parent1,[id2,[id3,"desc3"]
];
const obj = Object.fromEntries(array.map(a => [a[0],a[2]]));
console.log(obj);
,
作为一种好的做法,建议使用let
或const
而不是var
,因为var
“污染”了全局名称空间,因此这就是我的示例使用。
但是,如果您需要使用var
,则可以在示例中将const
替换为var
,这仍然可以。
给出以下源数组:
const array = [
[id1,"desc3"]
];
以下代码块使用子数组的第1个元素作为键,第3个元素作为值创建名为obj
的对象:
// Create an empty object
const obj = {};
// Iterate through the source array
array.forEach((element) => {
// Assign the 1st element of the sub-array as the property key
// and the 3rd element as the property value
obj[element[0]] = element[2];
});
console.log(obj);
这具有相同的效果,但更简单且占用空间更小:
const obj = Object.fromEntries(array.map(([key,_,value]) => [key,value]));
console.log(obj);