Tyler Mills
Tyler Mills

Reputation: 363

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"},
]

Upvotes: 2

Views: 291

Answers (3)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

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

Upvotes: 1

terpinmd
terpinmd

Reputation: 1028

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

Upvotes: 1

trincot
trincot

Reputation: 350147

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

Upvotes: 2

Related Questions