简体   繁体   中英

Lodash update values between arrays

I have got the two following array examples:

var a = [{ 
  id: 1560128,
  number: 'UNI01',
  state: 'PROGRESS',
  status: 1772627 
}];

var b = [ 
  { id: 92, description: 'In Studio'},
  { id: 93, description: 'Testing'},
  { id: 1772627, description: 'Active'}
];

I am wanting to create a new array or objects so that if status in array a matches with an id from array b, it will push the description value to the status key, and produce the following array:

var c = [{
  id: 1560128,
  number: 'UNI01',
  state: 'PROGRESS',
  status: 'Active'
}];

Is this possible with Lodash?

This is a way to do it with plain Javascript:

var a = [{
  id: 1560128,
  number: 'UNI01',
  state: 'PROGRESS',
  status: 1772627 
}];

var b = [
  { id: 92, description: 'In Studio'},
  { id: 93, description: 'Testing'},
  { id: 1772627, description: 'Active'}
];

var c = a.map(ae => {
  var be = b.find(be => be.id === ae.status);

  if (be) 
    return Object.assign({}, ae, { status: be.description });
  else
    return ae;
});

With lodash you can create a map of statuses by ids using _.keyBy() . Then _.map() array a and get the description from the statusMap using _.get() . Return a new object by using _.assign() :

 var a = [{ id: 1560128, number: 'UNI01', state: 'PROGRESS', status: 1772627 }]; var b = [{ id: 92, description: 'In Studio'}, { id: 93, description: 'Testing'}, { id: 1772627, description: 'Active'}]; var statusMap = _.keyBy(b, 'id'); // generate a map of statuses by id var c = _.map(a, function(o) { // get the status from the statusMap, if it doesn't exist use the original status as default var status = _.get(statusMap, '[' + o.status + '].description', o.status); // create a new object with the new status return _.assign({}, o, { status: status }); }); console.log(c); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

With ES6 you can the same thing using a Map , Array#map , and Object#assign :

 const a = [{ id: 1560128, number: 'UNI01', state: 'PROGRESS', status: 1772627 }]; const b = [{ id: 92, description: 'In Studio'}, { id: 93, description: 'Testing'}, { id: 1772627, description: 'Active'}]; const statusMap = new Map(b.map(({ id, description }) => [id, description])); // generate a map of statuses by id const c = a.map((o) => Object.assign({}, o, { // get the status from the statusMap, if it doesn't exist use the original status as default status: statusMap.get(o.status) || o.status })); console.log(c); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

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