2

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" }
]
0

3 Answers 3

2

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

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

1 Comment

You can reduce it to data.map(arr => arr.reduce((acc, val, i) => (acc[propertyName[i]] = val, acc), {})). I'll leave aside whether that is better readable.
1

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

Comments

0

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

Comments

Your Answer

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