简体   繁体   English

根据条件 javascript 将键值对附加到字典数组

[英]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:假设nodesObject而不是数组,并且X_Group是数组,您可以:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM