Lodash将对象添加到已排序的Obejct数组中

时间:2017-03-27 10:32:51

标签: javascript arrays node.js object lodash

我正在寻找将对象添加到已经排序的对象数组中。因此,在将新对象添加到其中之后,应该对新数组进行排序。

这是基于对象属性displayName

的排序数组
[
  {
    "id": "06BCCC25",
    "displayName":"Application"

  },
  {
    "id": "39F886D9", 
    "displayName":"Communication"
  },
  {
    "id": "22EA4ED5",
     "displayName":"Device"
  },
  {
    "id": "2F6E5FEA",
     "displayName":"Service"
  },
  {
    "id": "317BF72C", "displayName":"Service02"
  }

]

现在我要添加

{
    "id": "07BSSC25",
    "displayName":"Mail"

  }

所以在添加之后它将被放置在第3和第4个索引之间。

2 个答案:

答案 0 :(得分:4)

您可以使用_.sortedIndexBy(),请参阅:

例如,您可以使用:

array.splice(_.sortedIndexBy(array, value, iteratee), 0, value);

其中array是您的对象数组,value是要插入的新对象,iteratee是每个元素调用的函数,它返回您要对其进行排序的值,但它也可以是一个属性名称。

所以在你的情况下,这样的事情应该有效:

array.splice(_.sortedIndexBy(array, value, 'displayName'), 0, value);

只需替换array的数组名称和value的新对象。

另请参阅GitHub上的这个问题:

如果你经常使用它,你也可以添加一个lodash函数,例如:

_.insertSorted = (a, v) => a.splice(_.sortedIndex(a, v), 0, v);
_.insertSortedBy = (a, v, i) => a.splice(_.sortedIndexBy(a, v, i), 0, v);

你可以使用 - 在你的情况下

_.insertSorted(array, value, 'displayName');

答案 1 :(得分:0)

这是我们不带破折号的解决方案...

const records = [{ name: 'a'}, { name: 'b'}, { name: 'c'}, { name: 'd'}];
const newObjRecord = { name: 'e' };

// inserts into an already sorted array
// it still works, even if the array is empty
// it still works, even if the item should be the last
const inserted = records.some((record, index) => {
    if (record.name > newObjRecord.name) {
        records.splice(index, 0, newObjRecord);
        return true;
    }
    return false;
});
// if the array is empty or at the very end, insert it at the end
if (!inserted) records.push(newObjRecord);