如何基于多个属性组合单个对象数组

问题描述 投票:-1回答:1

利用javascript,我有一个对象数组,如下所示:

id |    date    | store |  type  | txn  | failed
------------------------------------------------
 1 |  10-02-18  |  32   |  short |  4   | false
 2 |  10-02-18  |  32   |  long  | null | true
 3 |  10-03-18  |  32   |  short |  7   | false
 4 |  10-03-18  |  32   |  long  |  10  | false

我希望能够将此数组转换为如下所示的内容:

[
 {
   date: 10-02-18,
   store: 32,
   short: {
     txn: 4,
     failed: false,
   },
   long: {
     txn: null,
     failed: true,
   },
 },
 {
   date: 10-03-18,
   store: 32,
   short: {
     txn: 7,
     failed: false,
   },
   long: {
     txn: 10,
     failed: true,
   },
 }
]

您可以看到我想将“type”,“txn”和“failed”属性与具有相同“date”和“storeId”的行组合,将“type”添加为属性并将“txn”和“failed” “作为”类型“的子属性。新数组中可以忽略“id”属性。

我使用lodash相当多,但这不是必需的。我只是在努力探索如何进行这种转变。

javascript node.js lodash
1个回答
1
投票

您基本上只需要创建一个对象,其中的键代表您想要的组所特有的内容。例如,您可以创建store_date连接的键,并且该对象将只有其中一个,如果您有商店和日期,它将很快获得。您可以使用reduce构建这样的对象。获得对象后,只需调用Object.values即可获取值数组。例如:

let arr = [
    {id:1, date: "10-02-18",store: 32, type: "short", tx: 4, failed: false},
    {id:2, date: "10-02-18",store: 32, type: "long", tx: null, failed: true},
    {id:3, date: "10-03-18",store: 32, type: "short", tx: 7, failed: false},
    {id:4, date: "10-03-18",store: 32, type: "long ", tx: 10, failed: false}
]

let obj = arr.reduce((obj, {id, date, store, type, tx, failed}) => {
    // make a unique key
    key = `${date}_${store}`

    // if we haven't seen this key add it with the outline of the object
    if(!obj[key]) obj[key] = {date, store}

    // add specific type to either the found obj or the new one
    obj[key][type] = {tx, failed}
    return obj
}, {})

// obj is an object keyed to date_store
// get just the values
console.log(Object.values(obj))
© www.soinside.com 2019 - 2024. All rights reserved.