gpt4 book ai didi

javascript - 如何将对象键设置为公分母?

转载 作者:行者123 更新时间:2023-12-02 18:11:54 25 4
gpt4 key购买 nike

我有一个对象数组,并希望数组中的每个对象都具有相同的键。

var obj1 = {"type": "test", "info": "a lot", "value": 7};
var obj2 = {"value": 5};
var obj3 = {"context": "demo", "info": "very long", "value": 3};
var obj4 = {"info": "no way"};

var dataSet = [obj1,obj2,obj3,obj4];

我的尝试是在第一步中创建一个包含所有可能键的数组。然后循环遍历该键数组并更新对象(如果未找到该键)。

keys.forEach(function(a,b){
dataSet.forEach(function(c,d){
//key not found
if(a in c === false)
{
//add key to object
dataSet[b][a] = false;
}
});
});

但是,它似乎无法正常工作。这是我的输出:

after logic:  [
{
"type": false,
"info": "a lot",
"value": 7
},
{
"value": 5,
"info": false
},
{
"context": "demo",
"info": "very long",
"value": false
},
{
"info": "no way",
"context": false
}
]

我错过了什么?

var obj1 = {"type": "test", "info": "a lot", "value": 7};
var obj2 = {"value": 5};
var obj3 = {"context": "demo", "info": "very long", "value": 3};
var obj4 = {"info": "no way"};

var dataSet = [obj1,obj2,obj3,obj4];
var keys = [];

console.log("before logic: ", dataSet);

//Step 1: Fill keys array
dataSet.forEach(function(a,b){
Object.keys(a).forEach(function(c,d)
{
//add keys to array if not already exists
if(!keys.includes(c))
{
keys.push(c);
}
});
});

//Step2: loop through keys array and add key to object if not existing
keys.forEach(function(a,b){
dataSet.forEach(function(c,d){
//key not found
if(a in c === false)
{
//add key to object
dataSet[b][a] = false;
}
});
});

console.log("after logic: ", dataSet);

编辑:

如果键也始终按相同顺序排序,那就完美了。

最佳答案

您可以将 key 收集到 Set 中使用flatMap() ,然后使用 forEach() 分配缺少的部分:

const dataSet = [
{"type": "test", "info": "a lot", "value": 7},
{"value": 5},
{"context": "demo", "info": "very long", "value": 3},
{"info": "no way"}
];

const keys = new Set(dataSet.flatMap(Object.keys));

dataSet.forEach((v) => keys.forEach((k) => v[k] = k in v ? v[k] : false));

console.log(dataSet);


为了满足键具有相同顺序的额外要求,请注意,从历史上看,JavaScript 对象属性是无序的,因此依赖 JavaScript 中对象属性的顺序几乎从来都不是一个好主意。

话虽如此,修改现有对象时很难获得固定的顺序,但如果创建新对象则可行:

const dataSet = [
{"type": "test", "info": "a lot", "value": 7},
{"value": 5},
{"context": "demo", "info": "very long", "value": 3},
{"info": "no way"}
];

const keys = [...new Set(dataSet.flatMap(Object.keys))];

const result = dataSet.map((v) => keys.reduce((a, k) => ({
...a,
[k]: k in v ? v[k] : false
}), {}));

console.log(result);

关于javascript - 如何将对象键设置为公分母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72182599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com