How can I convert an array of arrays to an array of objects, selecting the key from other array?

Viewed 68

For example, I have an array of properties (it's more than 3)

var propertyName = ["name", "esteira", "horse"];

and I have values of data (arrays of arrays):

var data = [["1", "2", "3"], ["3", "4", "5"], ["6", "7", "8"]];

How can I set the property key to the data?

I want to get at the result something like this:

[
  { name: "1", esteira: "2", horse: "3" },
  { name: "3", esteira: "4", horse: "5" },
  { name: "6", esteira: "7", horse: "8" }
]
3 Answers

You could use map with reduce method to get the result. Use reduce method to make the object and map for the resultant array.

const propertyName = ['name', 'esteira', 'horse'];
const data = [
  ['1', '2', '3'],
  ['3', '4', '5'],
  ['6', '7', '8'],
];
const ret = data.map((x) => {
  return x.reduce((prev, c, i) => {
    const p = prev;
    p[propertyName[i]] = c;
    return p;
  }, {});
});
console.log(ret);

This can be achieved using Object.fromEntries

  • map() over the data array
  • pass each nested array mapped against propertyNames array by index to Object.fromEntries()
const dataObjs = data.map(a => 
    Object.fromEntries(a.map((e,i) => [propertyName[i], e]))
  );

const propertyName = ['name', 'esteira', 'horse'];
const data = [
  ['1', '2', '3'],
  ['3', '4', '5'],
  ['6', '7', '8'],
];

const dataObjs = data.map(a => 
    Object.fromEntries(a.map((e,i) => [propertyName[i], e]))
  );

console.log(dataObjs);

You can use .map to transform your array of data, and assign the properties on a blank object. I don't know whether or not this is the most efficient way to solve the problem, but it gives the desired output.

var propertyName = ["name", "esteira", "horse"];
var data = [["1", "2", "3"], ["3", "4", "5"], ["6", "7", "8"]];

var result = data.map(datum => {
  const obj = {};
  for(const index in propertyName)
  {
    const prop = propertyName[index];
    obj[prop] = datum[index];
  }
  return obj;
});

console.log(result);

Related