使用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”添加和“失败”作为“类型”的子属性。新数组中的“ id”属性可以忽略。
我经常使用lodash,但这不是必需条件。我只是在努力地思考如何进行这种转换。
答案 0 :(得分: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))