简体   繁体   中英

Assign First Element of Nested Array as Property of Parent Object

Assuming the following Array:

[
{id: 1234, name: "@Acme", sources:["Twitter"]},
{id: 5678, name: "@Enron", sources:["Facebook"]},
]

I want to promote sources[0] to a property value, either under sources itself or as a new key using lodash .

I've done the following:

myList = _.map(monitorList, _.partialRight(_.pick, ['id', 'name', 'sources']));
mySources = _.map(monitorList, 'sources');

I imagine I can iterate through each respective array now and map my index from mySources to the sources key in myList , however it seems like there should be a functional way using lodash to promote a nested array item to a property value.

Ideal final data structure:

[
{id: 1234, name: "@Acme", sources:"Twitter"},
{id: 5678, name: "@Enron", sources:"Facebook"},
]

With a functional ES6 approach:

 const monitorList = [ {id: 1234, name: "@Acme", sources:["Twitter"]}, {id: 5678, name: "@Enron", sources:["Facebook"]}, ]; var result = monitorList.map(o => Object.assign({}, o, { sources: o.sources[0] })); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can follow a simple path and use forEach to replace sources property:

 var items = [{id: 1234, name: "@Acme", sources:["Twitter"]}, {id: 5678, name: "@Enron", sources:["Facebook"]}]; items.forEach((item) => item.sources = item.sources[0]); console.log(items); 

Another solution, using map , which is more functional (as it does not change items variable):

 var items = [{id: 1234, name: "@Acme", sources:["Twitter"]}, {id: 5678, name: "@Enron", sources:["Facebook"]}]; var newItems = items.map((item) => Object.assign({}, item, { sources: item.sources[0] })); console.log(newItems); 

You could use map:

var array = [{id: 1234, name: "@Acme", sources:["Twitter"]},
              {id: 5678, name: "@Enron", sources:["Facebook"]}];


var items = array.map(item => {
  item.source = item.sources[0]; 
  return item;
});

You could change item.source to item.sources as well if you wanted to overwrite.

Another way using some losdash methods:

var items = array.map(item => {
  return _.assign({}, item, {sources: _.first(item.sources)});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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