我将参考以下内容:测试对象物种对象。
在“物种”对象的内部,我有两个属性:“物种”和“状态”。"state“属性有一个值,它是一个带有状态的数组。我想为"test“对象创建一个键,它对应于位于对象物种对象中的" state”数组中的每个状态。
示例输出(查看下面的代码以了解这些值来自何处):
{a: ["tiger", "dog"], b: ["tiger"], c: ["dog","lion"], d: ["tiger", "dog"], e: ["lion:]}我的想法是,我想列出每个州的物种,而且物种通常不限于一个州,所以肯塔基州的一个物种也可能在俄亥俄州找到。我希望以上述方式将该物种列为这两个州的居民。
我收到的错误如下:
Uncaught (in promise) TypeError: test[d].append is not a function
at script.js:272
at Array.forEach (<anonymous>)
at runVis (script.js:270)
at script.js:178这是我的密码:
var test = new Object();
var species = [{species: "tiger", state: ["a","b","d"]},
{species: "dog", state: ["a","c","d"]},
{species: "lion", state: ["c", "e"]}
];
for (i in species) {
species[i].state.forEach(function(d) {
if (d in test) {
test[d].append(species[i].species)
}
else {
test[d] = [species[i].species];
console.log(test);
}
})
}如果状态还不存在,我会为它创建一个键。我还首次将该状态的物种的值存储在数组中。当我遇到一个物种生活在一个已经有密钥的状态时,我想把这个物种附加到数组中,这个数组是状态键的值。
发布于 2019-05-06 02:50:09
这是push而不是append
for (i in species) {
species[i].state.forEach(function(d) {
if (d in test) {
test[d].push(species[i].species)
} else {
test[d] = [species[i].species];
console.log(test);
}
})
}您也可以使用reduce,如下所示:
var species = [{species: "tiger", state: ["a","b","d"]},{species: "dog", state: ["a","c","d"]},{species: "lion", state: ["c", "e"]}];
var test = species.reduce((acc, { species, state }) => {
state.forEach(s => {
acc[s] = acc[s] || [];
acc[s].push(species);
});
return acc;
}, {});
console.log(test);.as-console-wrapper { max-height: 100% !important; top: auto; }
https://stackoverflow.com/questions/55998210
复制相似问题