我有以下两个数组示例:
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/