简体   繁体   English

我如何在 Lodash 中做到这一点?

[英]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?我怎样才能在 lodash 中做到这一点?

I tried the below method:我尝试了以下方法:

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

Using ES5 - iterate with Array#reduce with initial value of an empty object.使用 ES5 - 使用空对象的初始值迭代Array#reduce 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 .使用 ES6 - 使用Array#map迭代使用解构获取值,并使用计算属性名称设置。 Combine all to a single object by using Object#assign with the spread syntax :通过使用Object#assign扩展语法所有内容组合为一个对象:

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

You can do it with pure JS this way:您可以通过以下方式使用纯 JS 来实现:

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

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或者你也可以使用 lodash

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

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

But, if you really wanna learn more you can read this blog: Noobie Programmer: Lodas - The best 3rd party library for react and javascript developers但是,如果您真的想了解更多信息,可以阅读此博客: Noobie Programmer:Lodas - 适合 React 和 javascript 开发人员的最佳 3rd 方库

it teaches you the basics.它教你基础知识。 Once you mastered it you can do any complex data structures.一旦你掌握了它,你就可以做任何复杂的数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM