gpt4 book ai didi

javascript - 比较javascript中的两个对象数组

转载 作者:行者123 更新时间:2023-11-29 17:56:34 25 4
gpt4 key购买 nike

这是我的静态值,它有 id 和名称:

var staticValues = [
{ "id": "1", "name": "PEKKA" },
{ "id": "2", "name": "Golem" },
{ "id": "3", "name": "Vigilane" },
{ "id": "4", "name": "SpiderMan" },
{ "id": "5", "name": "Archer" },
{ "id": "6", "name": "SuperMan" }
]

这是我的方法返回的值:

var myReturnedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
]

我的输出需要是这样的:

var myReturnedValues = [
[ [ "Golem", "SpiderMan" ] ],
[ [ "Archer", "Archer" ] ],
[ [ "PEKKA", "Vigilante" ] ],
[ [ "SpiderMan", "Vigilante" ] ]
]

我想在这里做的是我必须比较 staticValuesmyReturnedValues 并根据它们的 id 返回名称,而不是只返回 id。我用 underscore.js 尝试了更多方法但失败了。有人可以给我一些想法吗?

我的方法是这样的:

var staticValues = [ /* here I have the whole static data */ ];

$scope.getCategories = function() {
var myReturnedValues = mainSteps.map(x => [x.steps.map(y => y.category)]);
return myReturnedValues;
}

编辑后的代码 ,

$scope.getCategories =function(){
var myReturnedValues =mainSteps.map(x => [x.steps.map(y => y.category+"\n"+"\n"+"\n")]);
//return myReturnedValues;
console.log('meeee before',angular.toJson(myReturnedValues));
newval = {};
$.each(staticValues ,function(i,v) {
console.log('meeee staticCategories',angular.toJson(staticValues ));
newval[v.id] = v.name;
});


$.each(myReturnedValues,function(i,v){
$.each(v[0],function(x,t){
myReturnedValues[i][0][x] = newval[t];
});
});
console.log('meeee after',angular.toJson(myReturnedValues));
return myReturnedValues;
}

最佳答案

首先将 staticValues 转换为 key => value 对象:

names = {}
staticValues.forEach(obj => names[obj.id] = obj.name);

然后迭代 myReturedValues 并在进行时用名称替换 ids:

var staticValues = [
{ "id": "1", "name": "PEKKA" },
{ "id": "2", "name": "Golem" },
{ "id": "3", "name": "Vigilane" },
{ "id": "4", "name": "SpiderMan" },
{ "id": "5", "name": "Archer" },
{ "id": "6", "name": "SuperMan" }
]

var myReturnedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
]

names = {}
staticValues.forEach(x => names[x.id] = x.name)

res = myReturnedValues.map(sub =>
[sub[0].map(id => names[id])]
)

console.log(res)

关于javascript - 比较javascript中的两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38607426/

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