我的对象如下:
const features = [{
'name': 'feature1', 'tags':
[{'weight':10, 'tagName': 't1'},{'weight':20, 'tagName': 't2'}, {'weight':30, 'tagName': 't3'}]
},
{
'name': 'feature2', 'tags':
[{'weight':40, 'tagName': 't1'}, {'weight':5, 'tagName':'t2'}, {'weight':70, 'tagName':'t3'}]
},
{
'name': 'feature3', 'tags':[
{'weight':50, 'tagName': 't1'}, {'weight':2, 'tagName': 't2'}, {'weight':80, 'tagName': 't3'}]
}]
我希望我的输出看起来像这样:
const features = [{'name':'feature1', 'weight':10, 'tagName':'t1'},
{'name':'feature1', 'weight':20, 'tagName':'t2'}, ...
{'name':'feature3', 'weight':80, 'tagName':'t3'}]
我尝试merge
和flatten
,但它不起作用。
更新1 我试过这个:
let feat = features;
results = []
_.each(feat, (item) => {
console.log(item);
results.push(_.flatten(_.pick(item.tags, 'weight'))); // pick for certain keys.
}
更新2 这解决了我的问题
_.each(features, (item) => {
_.each(item.tags, (itemTag) => {
results.push({'name':item.name, 'weight':itemTag.weight, 'tagName':itemTag.tagName})})})
但我想知道是否有更多lodash
方法可以做到这一点!
答案 0 :(得分:20)
以下方法使用flatMap来展平通过map获得的tags
。最后,使用spread operator分配tag
和feature
名称的值。
const result = _.flatMap(features, ({ name, tags }) =>
_.map(tags, tag => ({ name, ...tag }))
);
const features = [{
'name': 'feature1',
'tags': [{
'weight': 10,
'tagName': 't1'
}, {
'weight': 20,
'tagName': 't2'
}, {
'weight': 30,
'tagName': 't3'
}]
},
{
'name': 'feature2',
'tags': [{
'weight': 40,
'tagName': 't1'
}, {
'weight': 5,
'tagName': 't2'
}, {
'weight': 70,
'tagName': 't3'
}]
},
{
'name': 'feature3',
'tags': [{
'weight': 50,
'tagName': 't1'
}, {
'weight': 2,
'tagName': 't2'
}, {
'weight': 80,
'tagName': 't3'
}]
}
];
const result = _.flatMap(features, ({ name, tags }) =>
_.map(tags, tag => ({ name, ...tag }))
);
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
这是一个简单的JavaScript解决方案,在Array#reduce
的帮助下使用Array#map
和Array#concat
来展平数组。
const result = features.reduce(
(result, { name, tags }) => result
.concat(tags.map(tag => ({ name, ...tag }))),
[]
);
const features = [{
'name': 'feature1',
'tags': [{
'weight': 10,
'tagName': 't1'
}, {
'weight': 20,
'tagName': 't2'
}, {
'weight': 30,
'tagName': 't3'
}]
},
{
'name': 'feature2',
'tags': [{
'weight': 40,
'tagName': 't1'
}, {
'weight': 5,
'tagName': 't2'
}, {
'weight': 70,
'tagName': 't3'
}]
},
{
'name': 'feature3',
'tags': [{
'weight': 50,
'tagName': 't1'
}, {
'weight': 2,
'tagName': 't2'
}, {
'weight': 80,
'tagName': 't3'
}]
}
];
const result = features.reduce(
(result, { name, tags }) => result
.concat(tags.map(tag => ({ name, ...tag }))),
[]
);
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>