Search code examples
javascriptlodash

Return an Object Key and Value from an Array with lodash


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.


Solution

  • 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.