简体   繁体   中英

How to Convert a nested array to an object

I want to create an object from a nested array only 2 levels deep. The function I came up with returns

[{ key1: 'value1', key2: 'value2' }]

rather than

[{ key1: 'value1' }, {key2: 'value2' }]

I've also tried replacing the if statement with obj[elem[0]] = elem[1]; but get the same result.

How can I create separate objects for each nested array?

var array = [["key1", "value1"], ["key2", "value2"]]

function nestedArrToObj(array){

  let obj = {};

  for (let i=0; i < array.length;i++) {
    let elem = array[i];

    if (!(obj[elem[0]])) {
      obj[elem[0]] = elem[1]
    }
  }

  return [obj];
}

Using the function map

 let array = [["key1", "value1"], ["key2", "value2"]]; let result = array.map(([key, value]) => ({[key]: value})); console.log(result) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Using the function reduce

 let array = [["key1", "value1"], ["key2", "value2"]]; let result = array.reduce((a, c) => { let [key, value] = c; return [...a, {[key]: value}]; }, []); console.log(result) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Cross-browser and backend technology compatible approach:

 var array = [["key1", "value1"], ["key2", "value2"]]; var result = []; for(var a of array) { var value = a.pop(); var key = a.pop(); var object = {}; object[key] = value; result.push(object); } console.log(result) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Here's a version with map :

 console.log( [["key1", "value1"], ["key2", "value2"]] .map(x => {let obj = {}; obj[x[0]] = x[1]; return obj;}) ) 

Some of the newer features of the language make this a bit easier. This is an ES5 solution.

 var array = [["key1", "value1"], ["key2", "value2"]] function nestedArrToObj(array){ return array.reduce(function(previous, current) { let obj = {}; obj[current[0]] = current[1]; previous.push(obj); return previous; }, []); } console.log(nestedArrToObj(array)) 

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