我想用另一个数组中的值修改以下forEach结果,但无法正常工作。
const BbDescriptionDictionary = ['AAA' , 'BBB', 'CCC',]
const boardBasisOptionsModified = [];
this.boardBasisOptions.forEach( (value) => {
boardBasisOptionsModified.push({
"key": value, "value": BbDescriptionDictionary[value]
});
});
this.boardBasisOptions = boardBasisOptionsModified;
答案 0 :(得分:2)
您可以为.forEach
提供第二个参数,以指示boardBasisOptions
的索引。像这样:
this.boardBasisOptions.forEach( (value, index) => {
boardBasisOptionsModified.push({
"key": value, "value": BbDescriptionDictionary[index]
});
});
答案 1 :(得分:0)
您可能想在index
循环中添加forEach
参数:
(我还用一些值初始化了boardBasisOptions
)
请参见以下工作片段:
boardBasisOptions = ['key1', 'key2', 'key3'];
const BbDescriptionDictionary = ['AAA', 'BBB', 'CCC', ]
const boardBasisOptionsModified = [];
this.boardBasisOptions.forEach((value, index) => {
boardBasisOptionsModified.push({
"key": value,
"value": BbDescriptionDictionary[index]
});
});
this.boardBasisOptions = boardBasisOptionsModified;
console.log("boardBasisOptions:");
console.log(this.boardBasisOptions);
答案 2 :(得分:0)
您试图使用值而不是索引访问BbDescriptionDictionay
数组中的值。您必须使用索引来访问数组的值。
只需将index
添加为forEach
函数的第二个参数即可。
this.boardBasisOptions.forEach( (value, index) => {
boardBasisOptionsModified.push({
"key": value, "value": BbDescriptionDictionary[index]
});
});
答案 3 :(得分:0)
通过获取索引,您可以使用Array#map
代替Array#push
。
const BbDescriptionDictionary = ['AAA', 'BBB', 'CCC',]
this.boardBasisOptions = this
.boardBasisOptions
.map((key, index) => ({ key, value: BbDescriptionDictionary[index] }));
答案 4 :(得分:0)
您应该只使用from . import gender # pragma: no cover, NOQA: F401
来创建一个新的变异数组,而不用担心创建临时数组,对其进行变异然后分配它们。
Array.prototype.map()
覆盖这样的属性被认为是不好的做法,因此我将原来的const BbDescriptionDictionary = ['AAA' , 'BBB', 'CCC',]
// Map runs the function on each array item and returns a new array
// with mutated the return value of that function
// Note: ({ ... }) is a shorthand way of returning a value
// (object in this case) without a function body {}
this.boardBasisOptions = this.boardBasisOptions.map((key, index) => ({
// Shorthand way of assigning a variable to an object using the var
// name as the key
key,
value: BbDescriptionDictionary[index]
})
返回到新属性,并在以后使用它:
boardBasisOptions
希望有帮助