Murenrb
Murenrb

Reputation: 377

creating an object of arrays and values from an array of objects containing arrays and values in javascript

In the following code snippet, I am gathering variables from an array of objects and then combining them into a single new object with other variables. Here is a simplified example:

var y = 10; 
var x = [
  {name: "name1", values:[1,2,3]},
  {name: "name2", values:[3,4,5]}
];
var newObj = {y:[],x:[]}

for (var j=0;j<x.length;j++){
  newObj.x.push([])
  for (var i=0;i<x[j].values.length;i++){
    newObj.x[j].push(x[j].values[i]);
  }
}

newObj.y=y

console.log(newObj)

This works for what I am doing, but I am sure it is not even remotely best practices. What would be a more elegant way of organizing the values array from x into the new object with the single value for y?

Upvotes: 1

Views: 106

Answers (1)

Ori Drori
Ori Drori

Reputation: 193258

ES6:

You can use Array.map() to get an array of x values, and assign y using computed property names.

Note: I use ES6's arrow function, and object destructuring in the map's callback, but it's not a must. See ES5 version.

const y = 10; 
const x = [
  {name: "name1", values:[1,2,3]},
  {name: "name2", values:[3,4,5]}
];

const result = { 
  y, 
  x: x.map(({ values }) => values) // [...values] if you want a copy of the original values
};

console.log(result);

ES5:

Use Array.map() to get x values:

var y = 10; 
var x = [
  {name: "name1", values:[1,2,3]},
  {name: "name2", values:[3,4,5]}
];

var result = { 
  y: y, 
  x: x.map(function(o) {
    return o.values; // values.slice(0) if you want a copy of the original values
  })
};

console.log(result);

Upvotes: 2

Related Questions