混合两个对象数组并使用 ramda 添加属性
mix two array of object and add properties with ramda
我有如下两个数组:
['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
,否则为 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} ]
感谢您的帮助。
您可以使用 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);
您可以使用 ramda 的 zipWith
根据提供的函数组合两个列表
R.zipWith(
(item, tag) => R.assoc('selected', item.key === tag, item),
items,
tags
)
我可能会这样做:
const combine = curry((tags, data) =>
map(d => assoc('selected', contains(d.key, tags), d), data)
)
combine(tags, data)
如果我们尝试过,我相信我们可以免除这一点,但我认为没有理由这样做。
您可以在 Ramda REPL.
上看到实际效果
我有如下两个数组:
['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
,否则为 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} ]
感谢您的帮助。
您可以使用 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);
您可以使用 ramda 的 zipWith
根据提供的函数组合两个列表
R.zipWith(
(item, tag) => R.assoc('selected', item.key === tag, item),
items,
tags
)
我可能会这样做:
const combine = curry((tags, data) =>
map(d => assoc('selected', contains(d.key, tags), d), data)
)
combine(tags, data)
如果我们尝试过,我相信我们可以免除这一点,但我认为没有理由这样做。
您可以在 Ramda REPL.
上看到实际效果