Sachin Solanki
Sachin Solanki

Reputation: 701

How do I do this in Lodash?

I have a array like structure from database results

var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}, {name: 'c', age: 35}] 

I want to create a new object with values as key and value like below:

var new_arra  = {a: 23, b: 24, c: 35}

How can I do this in lodash?

I tried the below method:

var result = _.forEach(results, function(index) {
    var result = _.map(index, function(value, prop) {
        return {prop: prop, value: value};
    });
});

Upvotes: 1

Views: 195

Answers (4)

doppelgunner
doppelgunner

Reputation: 649

That's simple.

All you need to do is loop through each data and insert it into a new empty object. Ex.

let new_arra = {};

_.each(arr, a => {
 new_arra[a.name] = a.age
});

Upvotes: 0

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

you need these two line only

let newData = {};
arr.map((item)=>newData[item.name]=item.age);

console.log(newData);

or you can also do it using lodash

 let newData = {};
 _.map(arr,(item)=>newData[item.name]=item.age);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Using ES5 - iterate with Array#reduce with initial value of an empty object. On each iteration set the name as key, and the age as value.

var arr = [{name: 'a', age: 23}, {name: 'b', age: 24}, {name: 'c', age: 35}];

var result = arr.reduce(function(obj, o) {
  obj[o.name] = o.age;

  return obj;
}, {});

console.log(result);

Using ES6 - Iterate with Array#map get the values using destructuring, and set using computed property names. Combine all to a single object by using Object#assign with the spread syntax:

const arr = [{name: 'a', age: 23}, {name: 'b', age: 24}, {name: 'c', age: 35}];

const result = Object.assign({}, ...arr.map(({ name, age }) => ({ [name]: age })));

console.log(result);

Upvotes: 3

Mikhail Shabrikov
Mikhail Shabrikov

Reputation: 8509

You can do it with pure JS this way:

var arr = [{
  name: 'a',
  age: 23
}, {
  name: 'b',
  age: 24
}, {
  name: 'c',
  age: 35
}]

var result = {};

arr.forEach(function(item) {
  result[item.name] = item.age
});

console.log(result);

Another way with reduce:

var arr = [{
  name: 'a',
  age: 23
}, {
  name: 'b',
  age: 24
}, {
  name: 'c',
  age: 35
}];

var result = arr.reduce(function(store, item) {
  store[item.name] = item.age;
  return store;
}, {});

console.log(result);

Upvotes: 1

Related Questions