[英]how to get the values of one array of objects key based on values of another array of objects?
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}}
the output expected is预期的 output 是
const result = {{'name':'Paul', 'id': 12, 'amount':100}, {'name':'Luke', 'id': 12, 'amount': 250}}
I tried mapping the uids to get and array of values like我尝试映射 uid 以获取和数组值,例如
uids = [12, 23]
then然后
names = uids.map(key => object[key].name);
so that I could use them to map the keys and the names in the other object but couldn't figure it out I know it is basic javascript but I am new to this这样我就可以使用它们来 map 其他 object 中的键和名称,但无法弄清楚我知道这是基本的 javascript 但我是新手
You could simply map the object with the given keys.您可以使用给定的键简单地 map object。
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);
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);
First of all the structure of data
is wrong.首先data
的结构是错误的。 It should be an array.它应该是一个数组。 Then you could do this:然后你可以这样做:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.