javascript - Lodash 更新数组之间的值

标签 javascript arrays object lodash

我有以下两个数组示例:

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

我想要创建一个新的数组或对象,以便如果数组 a 中的状态与数组 b 中的 id 匹配,它将把描述值推送到状态键,并生成以下数组:

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

Lodash 可以做到这一点吗?

最佳答案

使用 lodash,您可以使用 _.keyBy() 按 ID 创建状态图。 。然后_.map()数组 a 并使用 _.get()statusMap 获取描述。使用 _.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>

使用 ES6,您可以使用 Map 进行同样的操作, Array#map ,和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>

关于javascript - Lodash 更新数组之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334609/

相关文章:

Ruby object to_s object id 的编码是什么?

javascript - 将动态矩形限制为一个

c - 在 C 中打印动态数组

javascript - 如何根据另一个数组的顺序对一个对象数组进行排序?

python - 从 numpy 代码中删除列表组件

c# - 有效的 C# 二维列表

android - 在 Android 上持久化数据的建议?

javascript - 仅当用户不滚动时滚动到底部

javascript - 如何让 div 仅包含上次(javascript)函数调用(如果多次调用)中的元素?

javascript - 异常后的清理(如 Eloquent JavaScript 中所述)