簡體   English   中英

使用相同的鍵對 2 個對象進行排序 Javascript

[英]Sort 2 objects with the same key Javascript

我有 2 個對象,我希望第二個對象與第一個對象的順序相同。

前任:

const obj1 = [
  { key: 1, id: 1, name: "John" },
  { key: 2, id: 2, name: "Ann" },
  { key: 3, id: 3, name: "Kate" }
];

const obj2 = [
  { key: 2, id: 2, name: "Ann" },
  { key: 1, id: 1, name: "John" },
  { key: 3, id: 3, name: "Kate" }
];

目的是讓obj2obj1的順序相同,但只按鍵排序。 我正在嘗試制作一個助手 function,它將傳遞 3 個參數:

function helper(obj1, obj2, key) {
  // return new object with sorted array do not modify existing
}

我可以對其中之一進行排序,但不能將 2object 組合在一起

我的想法是用hash map來存儲key obj2,然后循環遍歷key obj1對obj2進行排序

 const obj1 = [ {key: 1, id: 5, name: 'John'}, {key: 2, id: 5, name: 'John'}, {key: 3, id: 5, name: 'John'} ] const obj2 = [ {key: 2, id: 5, name: 'John'}, {key: 1, id: 5, name: 'John'}, {key: 3, id: 5, name: 'John'} ] function help(obj1, obj2, key) { const hashKeyObj2 = obj2.reduce((val, item) => { val[item[key]] = item; return val; }, {}); return obj1.map((item) => hashKeyObj2[item[key]]); } console.log(help(obj1, obj2, 'key'))

單線

let sorted = obj1.map(a => obj2.find(b => a.key === b.key))

此代碼段將從 obj1 順序對 obj2 進行排序:

 const obj1 = [ { key: 1, id: 5, name: 'John' }, { key: 3, id: 5, name: 'John' }, { key: 2, id: 5, name: 'John' }, ] const obj2 = [ { key: 2, id: 5, name: 'John' }, { key: 1, id: 5, name: 'Jane' }, { key: 3, id: 5, name: 'Tom' }, ] function helper(obj1, obj2, key) { const findIndex = (refValue) => obj1.findIndex((candidate) => candidate[key] === refValue) const comparator = (item1, item2) => findIndex(item1[key]) - findIndex(item2[key]) return [...obj2].sort(comparator) } const result = helper(obj1, obj2, 'key') console.log('result:', result)

一種使用lodash的方法

function sortArrayBasedOnKeys(
  array1: Record<string, number | string>[],
  array2: Record<string, number | string>[],
  key: string
) {
  const order = _.map(array1, key);
  return _.sortBy(array2, (item) => _.indexOf(order, item[key]));
}

首先,我們獲取 array1 中對象的放置順序,然后使用該順序對下一個數組進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM