混合两个对象数组并使用ramda

时间:2017-10-07 13:33:34

标签: javascript arrays json ramda.js

我有两个数组如下:

['TAG.u', 'TAG.c'] 

另一个是:

[{name:'some',key:'TAG.u'},
{name:'some new', key: 'TAG.b'}, 
{name:'some another' , key:'TAG.c'},
{name: 'some big' , key:'TAG.a'}]

现在我想将这两个数组混合在一个数组中,为每个相同的键创建新属性selected: true,为else创建false。如下所示:

resualt : [{name:'some', key: 'TAG.U',selected: true} ,
{name:'some another' , key:'TAG.c' , selcted: true},
{name:'some new', key: 'TAG.b',selected: false},
{name: 'some big' , key:'TAG.a' ,selected: false} ]

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用array.map()遍历第二个数组,并查看第一个数组中是否存在每个对象的key值。

var arr1 = ['TAG.u', 'TAG.c'];
var arr2 = [{
    name: 'some',
    key: 'TAG.u'
  },
  {
    name: 'some new',
    key: 'TAG.b'
  },
  {
    name: 'some another',
    key: 'TAG.c'
  },
  {
    name: 'some big',
    key: 'TAG.a'
  }
];

var result = arr2.map(v => {
  v.selected = arr1.indexOf(v.key) > -1;
  return v;
});

console.log(result);

答案 1 :(得分:1)

您可以使用ramda' zipWith根据提供的功能合并两个列表

R.zipWith(
  (item, tag) => R.assoc('selected', item.key === tag, item),
  items,
  tags
 )

答案 2 :(得分:1)

我可能会这样做:

Caused by: java.util.concurrent.ExecutionException: com.google.cloud.dataflow.worker.KeyTokenInvalidException: Unable to fetch data due to token mismatch for key ��
at com.google.cloud.dataflow.worker.repackaged.com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:500)
at com.google.cloud.dataflow.worker.repackaged.com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:459)
at com.google.cloud.dataflow.worker.repackaged.com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:76)
at com.google.cloud.dataflow.worker.repackaged.com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:62)
at com.google.cloud.dataflow.worker.WindmillStateReader$WrappedFuture.get(WindmillStateReader.java:309)
at com.google.cloud.dataflow.worker.WindmillStateInternals$WindmillValue.read(WindmillStateInternals.java:384)
... 16 more
Caused by: com.google.cloud.dataflow.worker.KeyTokenInvalidException: Unable to fetch data due to token mismatch for key ��
at com.google.cloud.dataflow.worker.WindmillStateReader.consumeResponse(WindmillStateReader.java:469)
at com.google.cloud.dataflow.worker.WindmillStateReader.startBatchAndBlock(WindmillStateReader.java:411)
at com.google.cloud.dataflow.worker.WindmillStateReader$WrappedFuture.get(WindmillStateReader.java:306)
... 17 more

如果我们尝试过,我相信我们可以做到这一点,但我没有理由这样做。

您可以在 Ramda REPL 上看到这一点。