当两个项目具有相同的mapValues
时,我正在使用groupBy
和keys
进行分组并创建typeId
。
例如原始数据为
{
"Name": "One",
"typeId": 1
},
{
"Name": "Two",
"typeId": 2
},
{
"Name": "One Two",
"typeId": 1
},
{
"Name": "Three",
"typeId": 3
},
{
"Name": "Three Two",
"typeId": 3
}
并通过使用groupBy
将对象与匹配的typeId
和omit
的对象typeId
中的const GroupedTypes = Object.entries(
_.mapValues(_.groupBy(data, 'typeID'), rlist =>
rlist.map(type => _.omit(type, 'typeID'))
)
);
分组为...
[
"1",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
[
{
"Name": "Two",
}
]
],
[
"3",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]
如期返回...
Name
但是,我也想从第一个Name
对象中的值0
添加[
"1",
"One",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
"Two",
[
{
"Name": "Two",
}
]
],
[
"3",
"Three",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]
的对象。因此最终以类似..
lodash
我一直在浏览result = pd.merge(master_df[['Symbol','Strike_Price']],child_df,on=['Symbol','Strike_Price'],indicator=True,how='right')
文档,但找不到有效的方法。我该如何实现?
答案 0 :(得分:3)
您可以使用reduce
根据// if it's the array
member.names[0].name
// or if it's not an array
member.name
对项目进行分组:
typeId
您需要创建一个累加器对象,每个const input=[{"Name":"One","typeId":1},{"Name":"Two","typeId":2},{"Name":"One Two","typeId":1},{"Name":"Three","typeId":3},{"Name":"Three Two","typeId":3}]
const merged = input.reduce((acc, { Name, typeId }) => {
acc[typeId] = acc[typeId] || [ typeId, Name, []];
acc[typeId][2].push({ Name });
return acc;
}, {})
console.log(Object.values(merged))
作为键,输出中需要的数组作为其值。如果密钥尚不存在,请添加typeId
作为值的密钥。这样,第一项的[ typeId, Name, []]
将出现在输出中。这就是累加器/ Name
的样子:
merged
然后使用Object.values()
将该对象的值作为数组获取
答案 1 :(得分:1)
只需用{
"1": [1, "One", [{ "Name": "One" }, { "Name": "One Two" }]],
"2": [2, "Two", [{ "Name": "Two" }]],
"3": [3, "Three", [{ "Name": "Three" }, { "Name": "Three Two" }]]
}
添加另一个map
。
splice
const FilterGuests = [{
"Name": "One",
"typeId": 1
}, {
"Name": "Two",
"typeId": 2
}, {
"Name": "One Two",
"typeId": 1
}, {
"Name": "Three",
"typeId": 3
}, {
"Name": "Three Two",
"typeId": 3
}];
const GroupedTypes = Object.entries(
_.mapValues(_.groupBy(FilterGuests, 'typeId'), rlist =>
rlist.map(roomType => _.omit(roomType, 'typeId'))
)
).map(e => {
e.splice(1, 0, e[1][0].Name);
return e;
});
console.log(GroupedTypes);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 2 :(得分:0)
使用_.map()
而不是_.mapValues()
,它也适用于对象,并返回一个数组。在地图的回调中,从第二个参数获取组键,获取第一个元素Name
,然后以请求的格式返回一个数组:
const FilterGuests = [{"Name":"One","typeId":1},{"Name":"Two","typeId":2},{"Name":"One Two","typeId":1},{"Name":"Three","typeId":3},{"Name":"Three Two","typeId":3}];
const GroupedTypes = _.map(
_.groupBy(FilterGuests, 'typeId'),
(rlist, key) =>
[
key,
_.get(rlist, '[0].Name'),
rlist.map(roomType => _.omit(roomType, 'typeId'))
]
)
console.log(GroupedTypes);
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>