[英]How to sort an array of objects in the order of another array containing the unique values of a property present in each object?
I have have two arrays, I want to merge them into one object. 我有两个数组,我想将它们合并为一个对象。 I have given some examples of what I have and what I want to achieve.
我已经举例说明了我所拥有和想要实现的目标。 I tried
_.union
and few other underscore methods. 我尝试了
_.union
和其他一些下划线方法。
var original = [
{
Country: 'US',
value: '10'
},
{
Country: 'Turkey',
value: '5'
}
];
var newlist =["Afghanistan", "Antarctica","Turkey"]
The Results I want: 我想要的结果:
var results= [
{
Country: 'Afghanistan',
value: '0'
},
{
Country: 'Antarctica',
value: '0'
},
{
Country: 'Turkey',
value: '5'
}
];
The US would not appear in the final results because the newlist doesn't have US. 美国将不会出现在最终结果中,因为新名单中没有美国。 So basically all the values from the new list would appear in the results with the values from the original list.
因此,基本上新列表中的所有值都会与原始列表中的值一起出现在结果中。
A non-Underscore solution, that .map()
s the new array, returning the object from the original array if it can .find()
it, otherwise returning a new object: 一个非下划线的解决方案,
.map()
是新数组,如果可以的话,从原始数组中返回该对象,如果它可以对.find()
返回,否则返回新对象:
var original = [ { Country: 'US', value: '10' }, { Country: 'Turkey', value: '5' } ]; var newlist =["Afghanistan", "Antarctica","Turkey"] var result = newlist.map(function(v) { return original.find(function(o) { return o.Country === v }) || { Country: v, value: '0' } }) console.log(result)
It's a one-liner with ES6 arrow functions: 它是具有ES6箭头功能的单线:
var original = [ { Country: 'US', value: '10' }, { Country: 'Turkey', value: '5' } ]; var newlist =["Afghanistan", "Antarctica","Turkey"] var result = newlist.map(v => original.find(o => o.Country===v) || {Country:v, value:'0'}) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.