我有一个如下所示的对象
{
UserId: "",
BidderId: "",
"1stDomestic.BidderId": "",
"1stDomestic.UserId": "234",
"1stEmployee.CreatedDate": "",
"1stIndependent.UpdatedDate": "",
"1stIndependent.CreateDate": ""
}
要求是我需要对点状对象键进行分组并创建如下输出
{
UserId: "",
BidderId: "",
1stDomestic: [
{
BidderId="",
UserId="234"
}
],
1stEmployee: [
{
CreatedDate=""
}
],
1stIndependent: [
{
UpdatedDate="",
CreatedDate=""
}
],
lstDomestic.BidderId = "",
1stDomestic.UserId="234",
1stEmployee.CreatedDate="",
1stIndependent.UpdatedDate=""
1stIndependent.CreateDate=""
}
我尝试使用几种方法来实现这一目标。 这里requestedData是对象
方法1
for (let prop in requestedData) {
if (prop.indexOf(".") > -1) {
mainKey[prop.split(".").pop()] = requestedData[prop];
requestedData[prop.substr(0, prop.indexOf("."))] = [mainKey];
}
}
console.log(requestedData)
上述方法为我提供了结构,但数组数据反射(reflect)的所有数据都是相同的。
1stDomestic: [
{
BidderId="",
UserId="234",
CreatedDate="",
UpdatedDate=""
}
],
1stEmployee: [
{
BidderId="",
UserId="234",
CreatedDate="",
UpdatedDate=""
}
],
1stIndependent: [
{
BidderId="",
UserId="234",
CreatedDate="",
UpdatedDate=""
}
]
方法2
for (let prop in requestedData) {
if (prop.indexOf(".") > -1) {
arr.push({
newProp: prop.substr(0, prop.indexOf(".")), //-->1
mainKey: prop.split(".").pop(), // --> 2
value: requestedData[prop] // -->3
});
}
}
console.log(Object.assign(requestedData, groupData(arr));
groupData(arrVal) {
let key = "newProp";
return resData.reduce((previous, current) => {
previous[current[key]] && previous[current[key]].length != 0
? previous[current[key]].push(current)
: (previous[current[key]] = new Array(current));
return previous;
}, {});
}
上述方法根据键对数据进行分组,但随后它创建具有 1,2 和 3 中属性的单独对象数组
我希望这就是上面提到的方式。 我现在有点陷入困境并试图解决这个问题。
我是这个论坛的新手,正在提问,如果我以某种方式使这个问题变得过于冗长和直观,请耐心等待。 帮助将不胜感激
最佳答案
您可以首先使用 reduce
基于键创建一个嵌套对象的对象,然后将原始对象与嵌套对象合并以获得最终结果:
const data = {
UserId: "",
BidderId: "",
"1stDomestic.BidderId": "",
"1stDomestic.UserId": "234",
"1stEmployee.CreatedDate": "",
"1stIndependent.UpdatedDate": "",
"1stIndependent.CreateDate": ""
};
const nested = Object.entries(data)
.filter(([k, v]) => k.includes('.'))
.reduce((acc, [k, v]) => {
const [parent, child] = k.split('.');
acc[parent] = acc[parent] || [{}];
acc[parent][0][child] = v;
return acc;
}, {});
const result = { ...data, ...nested};
console.log(result);
关于javascript - 如何在 Javascript 中对动态对象键进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58443878/