[英]Appending a key value pair to an array of dictionary based on a condition javascript
I have an array of dictionaries我有一系列字典
var nodes =
{
A: {'name' : 'A'},
B:{'name' : 'B'},
C:{'name' : 'C'},
D:{'name' : 'D'}
E:{'name' : 'E'}}
and和
another array另一个数组
var X_Group = ['A', 'B'];
I need to iterate through each of the dictionary elements and append group key with value X to them if it is present in the array X_Group and Y otherwise.如果数组 X_Group 中存在值 X,我需要遍历每个字典元素和 append 组键,否则为 Y。 ie.
IE。
var nodes =
{
A: {'name' : 'A' , group :'X'},
B:{'name' : 'B', group :'X'},
C:{'name' : 'C', group :'Y'},
D:{'name' : 'D', group :'Y'},
E:{'name' : 'E', group :'Y'}
}
I have tried:我努力了:
for (var key in nodes){
if (key in X_Group)
nodes[key].group = 'X';
else
nodes[key].group = 'Y';
}
But it does not work. Any suggestions on how to fix the issue?
You cannot use 'in' to check if a value is in an array.您不能使用“in”来检查值是否在数组中。 Use indexOf instead, which will return the index of the element, or -1.
改用 indexOf,它将返回元素的索引,或 -1。
Use this condition:使用这个条件:
if(X_Group.indexOf(nodes[key].name)!==-1)
Assuming nodes
is an Object
rather than array, and X_Group
is an array, you may:假设
nodes
是Object
而不是数组,并且X_Group
是数组,您可以:
nodes
array, using Object.assign()
nodes
阵列,使用Object.assign()
Object.assign()
(as its second parameter) spread array ( Array.prototype.map()
) of nodes
key-value pairs, appended with group
property, having 'X'
/ 'Y'
value based on whether it is found (with Array.prototype.includes()
) within X_Group
Object.assign()
(作为其第二个参数) nodes
键值对的扩展数组( Array.prototype.map()
),附加group
属性,根据是否为'X'
/ 'Y'
值在X_Group
中找到(使用Array.prototype.includes()
) const nodes = {A:{'name':'A'},B:{'name':'B'},C:{'name':'C'},D:{'name':'D'},E:{'name':'E'}}, X_Group = ['A', 'B'], result = Object.assign( {}, ...Object.keys(nodes).map(key => ({[key]: {...nodes[key], group: X_Group.includes(nodes[key].name)? 'X': 'Y' }}))) console.log(result)
.as-console-wrapper{min-height:100%;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.