gpt4 book ai didi

Javascript 用缺少的对象和值填充数组

转载 作者:行者123 更新时间:2023-12-03 12:32:16 24 4
gpt4 key购买 nike

我有一个像下面这样的数组,每个索引包含不同的对象集,我想创建一个统一的数据,其中每个索引中缺少的对象将具有 Value:0 ,

var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},

],
[

{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},

]
];

如何使用上面的数组获得如下所示的数组

var d = [
[
{axis:"Email",value:59,id:1},
{axis:"Social Networks",value:56,id:2},
{axis:"Sending Money",value:0,id:6},
{axis:"Other",value:0,id:7},

],
[
{axis:"Email",value:0,id:1},
{axis:"Social Networks",value:0,id:2},
{axis:"Sending Money",value:18,id:6},
{axis:"Other",value:15,id:7},

]
];

最佳答案

有两个功能:

getAllEntries 找到所有对象并将它们存储到变量 accEntries 中。然后 accEntries 用于搜索 d 的子数组中的所有事件。整个过程在 checkArray 中完成。

checkArray 用于获取 d 中所有已找到和未找到的条目。然后使用两个数组(找到的和未找到的)构建一个新的子数组,该子数组包含具有特定值的已找到条目和/或值为 0 的未找到条目。

希望对您有所帮助:

var d = [
[
{
axis: 'Email',
value: 59,
id: 1
},
{
axis: 'Social Networks',
value: 56,
id: 2
},
],
[
{
axis: 'Sending Money',
value: 18,
id: 6
},
{
axis: 'Other',
value: 15,
id: 7
},
]
];


function getAllEntries(array) {
var uniqueEntries = [];
array.forEach(function (subarray) {
subarray.forEach(function (obj) {
if (uniqueEntries.indexOf(obj) === - 1) uniqueEntries.push(obj);
});
});
return uniqueEntries;
}


function checkArray(array, acceptedEntries) {
var result = [];
array.forEach(function (subArray) {
var subResult = [];
var foundEntries = [];
subArray.forEach(function (obj) {
if (foundEntries.indexOf(obj.axis) === - 1) foundEntries.push(obj.axis);
});
var notFound = acceptedEntries.filter(function (accepted) {
return foundEntries.indexOf(accepted.axis) === - 1;
});
foundEntries.forEach(function (found) {
subArray.forEach(function (obj) {
if (obj.axis === found) subResult.push(obj);
});
});
notFound.forEach(function (notfound, index) {
subResult.push({
axis: notfound.axis,
value: 0,
id: notfound.id
});
});
result.push(subResult);
});
return result;
}


var accEntries = getAllEntries(d);
var result = checkArray(d, accEntries);
console.log(result);

关于Javascript 用缺少的对象和值填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42166799/

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