1

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?

1 Answer 1

2

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

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

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.