3

I have this Array, I need to get out each name and age value, and then make the name value a new key and the age value a new value.

The Array

var arr = [
 {name: "jack", age: 32 },
 {name: "jane", age: 34 }
]

My previous code

var monthlyProfit = _.map(arr, function(v) {
  var obj = {
    v.name: v.age
  };

  return obj;
});

console.log(monthlyProfit) // Error

Expectation

var arr = [
 {jack: 32},
 {jane: 34}
]

I am using lodash, but vanilla JS won't be a problem.

Akinjide
  • 2,723
  • 22
  • 28
  • 1
    http://stackoverflow.com/questions/19837916/javascript-creating-object-with-dynamic-keys might shed some light on why you're code isn't working. – Crescent Fresh Jun 09 '16 at 16:49

1 Answers1

6

The way you're currently trying to define the property will not work. There are multiple ways to achieve what you're trying to achieve, but I'd usually do it like this (using ES5):

var monthlyProfit = _.map(arr, function(v) {
  return {[v.name]  : v.age};
});

Or like this, as ES6 one-liners:

//using lodash
var monthlyProfit = _.map(arr, ({ name, age }) => ({ [name]: age }))

//or, pure ES6 without lodash:
var monthlyProfit = arr.map(({ name, age }) => ({ [name]: age }))

You should be seeing Syntax Error: Unexpected token . at the line where you're creating the object in your current code.

tex
  • 2,756
  • 22
  • 31