简体   繁体   English

使用对象变量将3个数组的数组转换为1个大数组

[英]Converting an array of 3 arrays into 1 big array with object variable

I'm new to StackOverflow and I know this post might possibly be a duplicate of another so please spare me with all the downvotes and if you think there's an answer to my question out there, please post it and I'll delete this question. 我是StackOverflow的新手,我知道这篇文章可能是其他文章的重复,因此请避免所有我的否决票,如果您认为我的问题有答案,请张贴它,我将删除此问题。 Thanks for understanding. 感谢您的理解。

var array1 = ["name", "title", "desc"]
var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]]

How will I turn these into: 我如何将它们变成:

[
 {name: "name1", title: "title1", desc: "desc1"},
 {name: "name2", title: "title2", desc: "desc2"}
]

You can use Array#map , Object.assign (with spread syntax ) and the ES6 computed property syntax to achieve that: 您可以使用Array#mapObject.assign (具有传播语法 )和ES6 计算属性语法来实现以下目的:

 const array1 = ["name", "title", "desc"], array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]]; const result = array2[0].map( (_, j) => Object.assign(...array1.map( (key, i) => ({ [key]: array2[i][j] }) )) ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

 const result = [];

 for(const [index, key] of array1.entries()){
   for(const [userindex, value] of array2[index].entries()){
     if(!result[userindex])
       result[userindex] = {};
     result[userindex][key] = value; 
   }
}

You might go over every key and the values related to the key and assign every key/value pair to the resulting object at the position of the value. 您可以遍历每个键和与该键相关的值,然后将每个键/值对分配给该值位置处的结果对象。

You could reduce the given values array by using the keys as key and the value for new objects. 您可以通过使用键作为键和新对象的值来减少给定值数组。

 var keys = ["name", "title", "desc"], values = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]], objects = values.reduce((r, a, i) => { a.forEach((v, j) => Object.assign(r[j] = r[j] || {}, { [keys[i]]: v })); return r; }, []); console.log(objects); 

You can use this way also: 您也可以使用这种方式:

 var array1 = ["name", "title", "desc"]; var array2 = [["name1", "name2"], ["title1", "title2"],["desc1", "desc2"]]; var res = []; for(var i=0; i<array2[0].length; i++){ var obj = {}; for(var j=0; j<array1.length; j++){ var key = array1[j]; var value = array2[j][i]; obj[key] = value; } res.push(obj); } console.log(res); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM