简体   繁体   中英

Create an object from an array of keys and an array of values

I have two arrays: newParamArr and paramVal .

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

Example values in the paramVal array: [ "Jon", 15, "jon@gmail.com" ] .

I need to create a JavaScript object that places all of the items in the array in the same object. For example { [newParamArr[0]]: paramVal[0], [newParamArr[1]]: paramVal[1], ... } .

In this case, the result should be { Name: "Jon", "Age": 15, "Email": "jon@gmail.com" } .

The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. That means newParamArr.length === paramVal.length will always hold.

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

Javascript Recursion for creating a JSON object

Recursively looping through an object to build a property list

 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

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

or the object spread syntax (ES2018):

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

or Object.fromEntries (ES2019):

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

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

Using ECMAScript2015:

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

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

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

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} 

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

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

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);

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

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 documentation for more

Object.fromEntries 接受一组键值元组并将压缩结果作为对象返回:

Object.fromEntries(keys.map((key, index)=> [key, values[index]]))

Use a loop:

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

This one works for me.

 var keys = ['foo', 'bar', 'baz']; var values = [11, 22, 33] var result = {}; keys.forEach(function(key, i){result[key] = values[i]}); console.log(result);

To achieve expected result, use below

var newParamArr = ["Name", "Age", "Email"];
var paramVal = ["Jon", "15", "jon@gmail.com"];
var obj = []
for (var i = 0; i < newParamArr.length; i++) {
  obj = obj + newParamArr[i] + ":" + paramVal[i] + ",";
}

obj = "{" + obj.substring(0, obj.length - 1) + "}"

console.log(obj)

https://codepen.io/nagasai/pen/pbXyKR

You can do this using javascript computed property names :

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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