I have an array of arrays like so:
var arr =
[
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
]
I need each subarray to be an object containing one key-value pair.
[
{"Id": "0011900000YDtPXAA1"},
{"Name": "account 50"},
...
]
I tried
var objArr = new Map(arr);
This produces the key value pairs I need, but puts them all in the same object. How can I get an array of smaller objects consisting of one kv pair each?
I would do something like:
var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; const newArr = arr.map(innerArr => ({[innerArr[0]]: innerArr[1]})); console.log(newArr);
var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; const newArr = arr.map(function (innerArr) { return {[innerArr[0]]: innerArr[1]}; }); console.log(newArr);
The map()
method creates a new array with the results of calling a provided function on every element in the calling array.
you could use a traditional for loop for this
var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; var arr2 = []; for (var i = 0; i < arr.length; i++) { var sub = {}; sub[arr[i][0]] = arr[i][1]; arr2.push(sub); } console.log(arr2);
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.