我试图找出将关联数组中的值乘以键匹配的对象内的值的最佳方法。
我有一个具有这种结构的javascript对象:
Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object, 13: Object, 14: Object, 15: Object, 16: Object, 17: Object, 18: Object, 19: Object, 20: Object}
0: Object
migforeign: 0.236575072366489
migmunicip: 0.0560288755282917
municipality: "Abrantes"
popdent: 0.0297202684601973
ppunit: 0.535590943544069
qagedep: 0.396652635764728
qfemale: 0.318397957136199
qfhh: 0.563231479514655
qforeign: 0.0569742908463333
qrental: 0.60538345279747
qurban: 0.507952069302096
__proto__: Object
1: Object
migforeign: 0.473038759939619
migmunicip: 0.09940842629884
municipality: "Alcanena"
popdent: 0.0653282502099797
ppunit: 0.72859029845259
qagedep: 0.30339392964618
qfemale: 0.306467891932506
qfhh: 0.685415625421922
qforeign: 0.27560826506132
qrental: 0.626947992275036
qurban: 0
__proto__: Object
2: Object ...
我有一个关联数组:
var assosArray = [migforeign: 8.3, migmunicip: 4, popdent: 3, ppunit: 10, qagedep: 3, qfemale: 2.5, qfhh: 8.3, qforeign: 8.5, qrental: 2, qurban: 2]
我正在尝试创建一个像这样的新对象:
Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object, 13: Object, 14: Object, 15: Object, 16: Object, 17: Object, 18: Object, 19: Object, 20: Object}
0: Object
migforeign: 1.96357310064186 // 0.236575072366489 * 8.3
migmunicip: 0.22411550211317 // 0.0560288755282917 * 4
municipality: "Abrantes"
popdent: 0.08916080538059 // 0.0297202684601973 * 3
ppunit: 5.35590943544069 // ...
qagedep: 1.18995790729418
qfemale: 0.7959948928405
qfhh: 4.67482127997164
qforeign: 0.48428147219383
qrental: 1.21076690559494
qurban: 1.01590413860419
__proto__: Object
1: Object ...
答案 0 :(得分:1)
这是你需要的吗?
var o = {};
o[0] = { migforeign: 0.236575072366489, migmunicip: 0.0560288755282917 };
o[1] = { migforeign: 0.473038759939619,
migmunicip: 0.09940842629884 }
var assoc = { migforeign: 8.3, migmunicip: 4 };
for(var p1 in o){
for(var p2 in o[p1]){
if(assoc.hasOwnProperty(p2)){
o[p1][p2] *= assoc[p2];
}
}
}
console.log(o);
答案 1 :(得分:0)
您的数组不是数组。它是一个具有属性和值的对象。这不起作用。
var assosArray = [migforeign: 8.3, migmunicip: 4, popdent: 3, ppunit: 10, qagedep: 3, qfemale: 2.5, qfhh: 8.3, qforeign: 8.5, qrental: 2, qurban: 2]
这将有效:
var assosArray = {
migforeign: 8.3,
migmunicip: 4,
popdent: 3,
ppunit: 10,
qagedep: 3,
qfemale: 2.5,
qfhh: 8.3,
qforeign: 8.5,
qrental: 2,
qurban: 2
};
您可以像这样循环您的对象:
var myNewObj = {};
for (prop in obj) {
if ( assosArray[prop] ) {
myNewObj[prop] = assosArray[prop] * obj[prop];
}
}
JSfiddle 看看你的控制台。
答案 2 :(得分:0)
你的“关联数组”甚至是有效的语法吗?我不这么认为 - 只需将它作为一个对象(在JavaScript中,它是一个字典)。
然后你可以做类似的事情:
for (var i = 0; values.length; ++i) {
for (var key in assosArray) {
if (assosArray.hasOwnProperty(key)) {
values[i][key] *= assosArray[key];
}
}
}