基于另一个javascript对象属性的javascript -sort数组

时间:2019-11-18 23:29:41

标签: javascript arrays sorting object compare

我有一个JavaScript数组和一个对象。需要帮助根据另一个数组中的订单号对javascript对象键进行排序

在子数组中,我有名称,订单号。需要根据该订单号对商品密钥进行排序

const subgroup = [
        {
            "code": "6748",
            "name": "test123",
            "orderNumber": "0"
        },
        {
            "code": "1234",
            "name": "customdata",
            "orderNumber": "1"
        }
    ]

 const offerings = {
        "customdata" : [
    {
        "code": "Audi",
        "color": "black"
      }
    ],
        "test123" : [
    {
        "brand": "Audi",
        "color": "black"
      }
    ]
 }

1 个答案:

答案 0 :(得分:0)

我相信这应该对您有用。我在代码中添加了一些注释,希望它们可以很好地解释正在发生的事情。

var subgroup = [{
    "code": "6748",
    "name": "test123",
    "orderNumber": "0"
  }, {
    "code": "1234",
    "name": "customdata",
    "orderNumber": "1"
  }];

var offerings = {
    "customdata": [{
        "code": "Audi",
        "color": "black"
    }],
    "test123": [{
        "brand": "Audi",
        "color": "black"
    }]
}

function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
  // Get copy of refArray
  let reference = refArray.slice();

  // Sort sortObject [ into an array at this point ]
  let sorted = [];
  for (let key in sortObject) {
    // Searches the refArray for the linkKey, and returns the intended index
    let index = reference.find((item) => item[linkKey] === key)[orderKey];
    // Places the sortObject's value in the correct index of the 'sorted' Array
    sorted[parseInt(index)] = [key, sortObject[key]];
  };

  // Return an object, created from previous 'sorted' Array
  return sorted.reduce((obj, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});
};

offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');

console.log(offerings);