我正在尝试使用基于另一个数组的值的json obejct的文本值填充数组
我的代码是:
var DemoOptions = {
"One" : 1,
"Two" : 2,
"Three" : 3,
"Four" : 4,
"Five" : 5
};
var OldArray = [1,3,5];
var NewArray = [];
$.each(OldArray,function(x, item){
NewArray.push(DemoOptions.item);
});
NewArray现在应该是:
NewArray ["One", "Three", "Five"]
答案 0 :(得分:3)
如果DemoOptions被翻转为:
var DemoOptions = {
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five"
};
您可以非常轻松地执行此操作,因为您只需要遍历OldArray
一个并将相应的值(由DemoOptions
映射)推送到NewArray
。由于你可能有另一种方式使用它,你应该动态创建这个翻转的副本,然后填充你的新数组:
var DemoOptions = {
"One" : 1,
"Two" : 2,
"Three" : 3,
"Four" : 4,
"Five" : 5
};
var OldArray = [1,3,5];
var flipped = {};
for(var key in DemoOptions)
flipped[DemoOptions[key]] = key;
var NewArray = [];
for(var i = 0; i < OldArray.length; i++)
NewArray.push(flipped[OldArray[i]]);
答案 1 :(得分:1)
太糟糕DemoOptions没有被数值而不是字符串值索引。无论如何,这个怎么样:
for (var index in OldArray) {
var value = OldArray[index];
for (var demoString in DemoOptions) {
if (DemoOptions.hasOwnProperty(demoString)) {
var demoValue = DemoOptions[demoString];
if (value == demoValue) {
NewArray.push(demoString);
break;
}
}
}
}