0

Given a JavaScript multi-dimensional array (data1) is there an easy way to transform it into an array of objects with dynamically generated property names (data2)? ES6 is fine.

var data1 = [
  [1,"Text A",4,2,"Yes"],
  [2,"Text B",3,3,"Yes"],
  [3,"Text C",1,2,"No"]
]

var data2 = [
  {"0":1,"1":"Text A","2":4,"3":2,"4":"Yes"},
  {"0":2,"1":"Text B","2":3,"3":3,"4":"Yes"},
  {"0":3,"1":"Text C","2":1,"3":2,"4":"No"}
]

2 Answers 2

3

var data1 = [
    [1,"Text A",4,2,"Yes"],
    [2,"Text B",3,3,"Yes"],
    [3,"Text C",1,2,"No"]
]

let data2 = data1.map(row => Object.assign({},row));

console.log(data2);

/*
[
  {
    "0": 1,
    "1": "Text A",
    "2": 4,
    "3": 2,
    "4": "Yes"
  },
  {
    "0": 2,
    "1": "Text B",
    "2": 3,
    "3": 3,
    "4": "Yes"
  },
  {
    "0": 3,
    "1": "Text C",
    "2": 1,
    "3": 2,
    "4": "No"
  }
]
*/

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

3 Comments

nice, efficient, elegant.
This answer is more clean, I like it
I had no idea Object.assign() could be used that way. Very nice.
1

This seems like a use case for mapping over the data1 array to return an array of transformed objects, and reducing over the subarrays to create those dynamic keys with values corresponding to the elements of the sub arrays.

const data1 = [
  [1,"Text A",4,2,"Yes"],
  [2,"Text B",3,3,"Yes"],
  [3,"Text C",1,2,"No"]
];

const data2 = data1.map(subArr => {
  // use reduce on each subarray to return objects
  return subArr.reduce((obj, curVal, curIdx) => {
    // set object key equal to the index, and value to current element
    obj[curIdx] = curVal;
    // return object to accumulate
    return obj;
  }, {})
});

console.log(data2); 
// [
//  {"0":1,"1":"Text A","2":4,"3":2,"4":"Yes"},
//  {"0":2,"1":"Text B","2":3,"3":3,"4":"Yes"},
//  {"0":3,"1":"Text C","2":1,"3":2,"4":"No"}
// ]

1 Comment

I were trying to get the result and finished with the same code as esinator, so I think is the fastest approach

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.