从两个数组创建一个 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39127989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:14:23  来源:igfitidea点击:

Creating a JavaScript Object from two arrays

javascript

提问by georg

I have two arrays: newParamArr[i]and paramVal[i].

我有两个数组:newParamArr[i]paramVal[i]

Example values in the newParamArr[i]array: ["Name", "Age", "Email"]

newParamArr[i]数组中的示例值: ["Name", "Age", "Email"]

Example values in the paramVal[i]array: ["Jon", "15", "[email protected]"]

paramVal[i]数组中的示例值: ["Jon", "15", "[email protected]"]

I need to create a JavaScript object that places all of the items in the array in the same object. For example

我需要创建一个 JavaScript 对象,将数组中的所有项目放在同一个对象中。例如

{newParamArr[0]:paramVal[0], newParamArr[1]:paramVal[1], ...}

{newParamArr[0]:paramVal[0], newParamArr[1]:paramVal[1], ...}

The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. As in...

两个数组的长度始终相同,但数组的长度可以增加或减少。就像在...

newParamArr.length === paramVal.lengthwill always returns true.

newParamArr.length === paramVal.length将始终返回 true。

None of the below posts could help to answer my question:

以下帖子均无法回答我的问题:

Javascript Recursion for creating a JSON object

用于创建 JSON 对象的 Javascript 递归

Recursively looping through an object to build a property list

递归遍历对象以构建属性列表

回答by georg

var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]

var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);

Alternatively, you can use Object.assign

或者,您可以使用 Object.assign

result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))

or the object spread syntax (ES2018):

或对象传播语法(ES2018):

result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})

or Object.fromEntries(ES2019):

Object.fromEntries(ES2019):

Object.fromEntries(keys.map((_, i) => [keys[i], values[i]]))

In case you're using lodash, there's _.zipObjectexactly for this type of thing.

如果您正在使用 lodash,那么_.zipObject正是针对这种类型的。

回答by craigmichaelmartin

Using ECMAScript2015:

使用 ECMAScript2015:

const obj = newParamArr.reduce((obj, value, index) => {
    obj[value] = paramArr[index];
    return obj;
}, {});

(EDIT) Previously misunderstood the OP to want an array:

(编辑)以前误解了 OP 想要一个数组:

const arr = newParamArr.map((value, index) => ({[value]: paramArr[index]}))

回答by Space Games

I know that the question is already a year old, but here is a one-line solution:

我知道这个问题已经有一年了,但这里有一个单行解决方案:

Object.assign( ...newParamArr.map( (v, i) => ( {[v]: paramVal[i]} ) ) );

回答by Chris Rollins

The following worked for me.

以下对我有用。

//test arrays
var newParamArr = [1, 2, 3, 4, 5];
var paramVal = ["one", "two", "three", "four", "five"];

//create an empty object to ensure it's the right type.
var obj = {};

//loop through the arrays using the first one's length since they're the same length
for(var i = 0; i < newParamArr.length; i++)
{
    //set the keys and values
    //avoid dot notation for the key in this case
    //use square brackets to set the key to the value of the array element
    obj[newParamArr[i]] = paramVal[i];
}

console.log(obj);

回答by uribalb

You can use Object.assign.apply()to merge an array of {key:value} pairs into the object you want to create:

您可以使用Object.assign.apply()将一组 {key:value} 对合并到您要创建的对象中:

Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) )

A runnable snippet:

一个可运行的片段:

var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]

var result =  Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) );
console.log(result); //returns {"foo": 11, "bar": 22, "baz": 33}

See the documentationfor more

查看文档了解更多

回答by technicalbloke

I needed this in a few places so I made this function...

我在几个地方需要这个所以我做了这个功能......

function zip(arr1,arr2,out={}){
    arr1.map( (val,idx)=>{ out[val] = arr2[idx]; } );
    return out;
}


console.log( zip( ["a","b","c"], [1,2,3] ) );

> {'a': 1, 'b': 2, 'c': 3} 

回答by Jacob

Use a loop:

使用循环:

var result = {};
for (var i = 0; i < newParamArr.length; i++) {
  result[newParamArr[i]] = paramArr[i];
}

回答by Hoque MD Zahidul

You can do this using javascript ES 6 new feature :

您可以使用 javascript ES 6 新功能执行此操作:

For example :

例如 :

var keys = ['zahid', 'fahim', 'hasib' ,'iftakhar'];

var ages = [11, 22, 33 ,31];

var testObject = {
    [keys.shift()] : ages.shift(),
    [keys.shift()] : ages.shift(),
    [keys.shift()] : ages.shift(),
    [keys.shift()] : ages.shift()

};

console.log(testObject); // { zahid: 11, fahim: 22, hasib: 33, iftakhar: 31 }