简体   繁体   English

lodash:仅深度复制数组中的几个属性

[英]lodash: deep copy only few properties from an array

I have an array with the below properties我有一个具有以下属性的数组

data = [ { 'id' : 1,
'name': 'xyz',
'age': 21,
'gender': 'M',
'address': '123 xyz'},
{ 'id' : 2,
'name': 'abc',
'age': 23,
'gender': 'F',
'address': '456 abc'}
]

I am trying to build an new array with just few of the properties and update a property (address) like this我正在尝试用几个属性构建一个新数组并像这样更新一个属性(地址)

data1= [ { 'id': 1, 'name': 'xyz', 'address1': '123 xyz'}, { 'id': 2, 'name': 'abc', 'address1': '456 abc'} ] data1= [ { 'id': 1, 'name': 'xyz', 'address1': '123 xyz'}, { 'id': 2, 'name': 'abc', 'address1': '456 abc '}]

I tried using map and remove functions.我尝试使用 map 并删除功能。 But wanted to see if there is an easy way to do it.但想看看是否有一种简单的方法可以做到这一点。 I tried using combinations of some of the lodash functions but not successful.我尝试使用一些 lodash 函数的组合,但没有成功。

How about just using the map function ?仅使用map function怎么样?

 var data = [{ 'id': 1, 'name': 'xyz', 'age': 21, 'gender': 'M', 'address': '123 xyz' }, { 'id': 2, 'name': 'abc', 'age': 23, 'gender': 'F', 'address': '456 abc' } ]; var data1 = data.map(x => ({id: x.id, name: x.name, address1: x.address})); // modify data data[0].id = 3; // only data has been modified, not data1 console.log(data); console.log(data1);

let data1 = data.map(d => {
return {'id' : d.id, 'name': d.name, 'address1': d.address}
})

Just a simple map is enough, no need of any lib.只需一个简单的 map 就足够了,不需要任何库。

I'd use map with destructuring, and shorthand property notation to create the new objects:我会使用map与解构和速记属性符号来创建新对象:

// Extracts `id`, `name`, and `address`...
//     \−−−−−−−−−−−−−−−  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const result = data.map(({id, name, address: address1}) => ({id, name, address1}));
// Renames `address` to `address1` −−−−−−−−^^^^^^^^^^       ^^^^^^^^^^^^^^^^^^^^
// Builds new object with result −−−−−−−−−−−−−−−−−−−−−−−−−−/

Live example:现场示例:

 const data = [ { 'id': 1, 'name': 'xyz', 'age': 21, 'gender': 'M', 'address': '123 xyz'}, { 'id': 2, 'name': 'abc', 'age': 23, 'gender': 'F', 'address': '456 abc'} ]; const result = data.map(({id, name, address: address1}) => ({id, name, address1})); console.log(result);

Or you can do the renaming when creating the new object:或者您可以在创建新的 object 时进行重命名:

const result = data.map(({id, name, address}) => ({id, name, address1: address}));

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

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