[英]How to insert particular value based on some matches inside an object
I have two objects with the following structure: 我有两个具有以下结构的对象:
var one = {
'26-34-1' : 100,
'26-34-84' : 101
};
var two = [
{
from : { id: '34', sid: '26' },
to : { id: '1', sid: '26' }
},
{
from : { id: '34', sid: '26' },
to : { id: '84', sid: '26' }
}
];
The keys in one
(eg. 26-34-1) identify an object in two
in the format: one
(例如26-34-1)中的键以two
格式标识一个对象:
from.sid
- from.id
- to.id
from.sid
- from.id
- to.id
What I need to do is insert the value from one
into two
if the key in one
matches. 我需要做的是,如果
one
键匹配,则将值从one
插入到two
。 Resulting in: 导致:
var two = [
{
from : { id: '34', sid: '26' },
to : { id: '1', sid: '26' },
oneid : { id: 100 }
},
{
from : { id: '34', sid: '26' },
to : { id: '84', sid: '26' },
oneid : { id: 101 }
}
];
I can't seem to figure it out, I think it's done with "mapping" but wasn't able to map from.sid
, from.id
and to.id
. 我似乎无法弄清楚,我认为它是通过“映射”完成的,但是无法映射
from.sid
, from.id
和to.id
Can someone please shed some light on this? 有人可以说明一下吗?
Edit : As I understand from another answer it's not what TS was asking about, my in case he doesn't have two
yet next code will do what's needed. 编辑 :据我从另一个答案中了解到,这不是TS的要求,以防万一他没有
two
但下一个代码将满足所需。
for (var key in one) {
var values = key.split('-');
var object = {
from: {
id: values[1],
sid: values[0]
},
to: {
id: values[2],
sid: values[0]
},
oneid: {
id: one[key]
}
};
two.push(object);
}
two.forEach(function(o){
var key = [o.from.sid, o.from.id, o.to.id].join('-');
if(key in one) o.oneid = { id: one[key] };
});
in
operator in
运营商
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.