排序与另一组ID匹配的对象的数组 [英] Sorting array of objects matching ids on a different set

查看:71
本文介绍了排序与另一组ID匹配的对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组

array = [
    {id: 5, name: "Helen", age: 20}, 
    {id: 15, name: "Lucy", age: 30}, 
    {id:7, name: "Carlos", age: 1}
]

然后我有一个类似的数组,但排序不同

Then I have a similar array sorted differently

arraySorted = [        
    {id: 15, name: "Lucy", age: 2}, 
    {id: 5, name: "Lara", age: 11}, 
    {id:7, name: "Carlos", age: 10}
]

两个数组上的对象ID始终匹配,其余属性可能相同也可能不相同.

The ids of the objects on both arrays will always match, the rest of the properties may or may not.

我需要按照与arraySorted相同的id顺序对数组进行排序.

What I need is sorting the array in the same id order as arraySorted.

(也可以在普通的JavaScript上完成,lodash不是必需的,但也许会有用)

(it can be also done on plain JavaScript, lodash is not necessary but maybe it will be useful)

推荐答案

而不是sort,而是使用mapfindObject.assign

Rather than sort, use map, find and Object.assign instead

arraySorted.map( s => Object.assign( s, array.find( t => t.id == s.id ) ) );

演示

var array = [{
    id: 5,
    name: "Helen",
    age: 20
  },
  {
    id: 15,
    name: "Lucy",
    age: 30
  },
  {
    id: 7,
    name: "Carlos",
    age: 1
  }
];
var arraySorted = [{
    id: 15,
    name: "Lucy",
    age: 2
  },
  {
    id: 5,
    name: "Lara",
    age: 11
  },
  {
    id: 7,
    name: "Carlos",
    age: 10
  }
];
array = arraySorted.map(s => Object.assign(s, array.find(t => t.id == s.id)));

console.log(array);

这篇关于排序与另一组ID匹配的对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆