0

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 k-v pair each?

2 Answers 2

3

I would do something like:

1. Arrow function

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

2. Not arrow function

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You have a syntax error. {innerArr[0]: innerArr[1]} should be {[innerArr[0]]: innerArr[1]}.
I used the arrow function after your edit. It works perfectly. Thank you!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.