data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
}
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}}
预期输出是
const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}
我尝试映射uid以获取和值数组,如
uids = [12, 23]
然后
names = uids.map(key => object[key].name);
这样我就可以用它们来映射另一个对象中的键和名称,但无法弄清楚 我知道这是基本的javascript,但我是新手
答案 0 :(得分:0)
您可以简单地使用给定的键映射对象。
var array = [12, 23],
object = { 12: { name: 'Paul', id: 12 }, 20: { name: 'Mike', id: 20 }, 41: { name: 'Jack', id: 41 }, 23: { name: 'Luke', id: 23 } },
result = array.map(key => object[key]);
console.log(result);
答案 1 :(得分:0)
var data = {
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
};
var object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}};
var uids = [12, 23];
mappedValues = uids.map(key => object[key]);
var result = mappedValues.map((item, i) => Object.assign({}, item, data[i]));
console.log(result);
答案 2 :(得分:0)
首先data
的结构是错误的。它应该是一个数组。然后,您可以这样做:
data = [
{'uid': 12, 'amount': 100},
{'uid': 23, 'amount': 250}
];
object = {12:{'name':'Paul', 'id':12}, 20:{'name':'Mike', 'id':20}, 41:{'name':'Jack', 'id':41}, 23:{'name':'Luke', 'id':23}};
for(let key in object){
var match = data.filter(i=>i.uid.toString() === key);
if(match && match.length){
object[key].amount = match[0].amount;
}
}
console.log(object)