如何使用 Lodash
更新数组元素值与其他数组元素数据值var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]
var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]
我认为可以做到:
_.chain()
.mapValues( ...blá blá... )
.values()
.value();
预期结果:
var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]
答案 0 :(得分:2)
您不需要执行mapValues
,因为您正在迭代集合而不是对象,mapKeys
和mapValues
更适合迭代对象并映射到另一个
现在,接近1,如果您想运行会返回预期商品的新数组的内容,请尝试map
这样的
var EXPECTED_RESULT = _.map(Master_Array, function(item){
var newItem = {};
newItem.Name = item.Name;
newItem.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
return newItem;
});
如果你想修改现有的数组,那么只需通过loadash或普通的javascript循环循环它,然后执行操作
_.each(Master_Array,function(item){
item.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
} )
答案 1 :(得分:1)
包含map
和find
的解决方案:
var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];
var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];
Master_Array = Master_Array.map((person) => ({
Name: person.Name,
Region: Regions_Map.find((region) => region.Region === person.Region).NewRegion
}));
console.log(Master_Array);
答案 2 :(得分:0)
javascript解决方案
var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];
var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];
var result = [];
Master_Array.forEach(function(data){
var temp = Regions_Map.filter(function(map){
if(map.Region === data.Region){
return map;
}
});
if(temp){
result.push({
Name : data.Name,
NewRegion: temp[0].NewRegion
});
}
});
console.log(result);