[英]Unflattening an array of objects in ES6
给定这样的对象的javascript数组:
[ { type: 'type1',
target: 'target1',
intent: 'intent1',
pattern: 'pattern1' },
{ type: 'type1',
target: 'target2',
intent: 'intent1',
pattern: 'pattern2' },
{ type: 'type2',
target: 'target1',
intent: 'intent2',
pattern: 'pattern3' } ]
如何使用ES6创建这样的对象?
[{
uniqueKey: 'intent1',
patterns: [{
type: 'type1',
target: 'target1',
pattern: 'pattern1'
}, {
type: 'type1',
target: 'target2',
pattern: 'pattern2'
}]
}, {
uniqueKey: 'intent2',
patterns: [{
type: 'type2',
target: 'target1',
pattern: 'pattern3'
}]
}]
我已经看到了很多带有reduce
, map
, filter
, set
, [...arr]
的示例,但是我一直在努力地将它们简洁地结合在一起。
这样的事情行吗? 它可能不是最有效的,但是我认为它会在给定示例数据集的情况下满足您的需求。
const collection = [
{ type: 'type1',
target: 'target1',
intent: 'intent1',
pattern: 'pattern1'
},
{ type: 'type1',
target: 'target2',
intent: 'intent1',
pattern: 'pattern2'
},
{ type: 'type2',
target: 'target1',
intent: 'intent2',
pattern: 'pattern3'
}
];
// Iterate through your collection, building on arr which
// starts out as an empty array when certain conditions are met.
const result = collection.reduce((arr, item) => {
const key = item.intent;
const pattern = {
type: item.type,
target: item.target,
pattern: item.pattern
};
// Check if an there's an existing entry with the current key
if (arr.length > 0 && arr.some(entry => entry.uniqueKey === key)) {
// If so, push the current pattern object into the existing entry's
// patterns key.
const existingEntry = arr.findIndex(entry => entry.uniqueKey === key);
arr[existingEntry].patterns.push(pattern)
// If there's no existing entry with the current key
} else {
// Create a new entry with the current key and pattern
const formattedEntry = {
uniqueKey: key,
patterns: [pattern]
}
arr.push(formattedEntry);
}
return arr
}, []);
console.log('result', result);
// output - returns an array with two objects, the first with a patterns array
// containing two objects matching the uniqueKey: intent1. The other
// with a patterns array containing one object matching uniqueKey: intent2.
// [{
// patterns: [
// {
// type: 'type1',
// target: 'target1',
// pattern: 'pattern1'
// },
// {
// type: 'type1',
// target: 'target2',
// pattern: 'pattern2'
// }
// ],
// uniqueKey: 'intent1',
// },
// {
// patterns: [{
// pattern: 'pattern3'
// target: 'target1',
// type: 'type2',
// }]
// uniqueKey: 'intent2',
// }]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.