在数组中插入元素



我有一个函数

checkName(output) {
output.filter((NewData) => {
return this.props.elements.filter((OldData) => {
if (NewData.key == OldData.key) {
NewData.name = OldData.name,
//there i need to add another element 
// Need to add newData.number = OldData.number
}
return NewData
})
})

return output
}

,我这样调用这个函数:

const named = this.checkName(product.rows)

现在我需要将值"OldData.Number"添加到我传递给checkName的产品数组中。";newData.Number"在product中没有定义(所以我需要创建这个字段)

例如:

checkName函数前的产品

product.rows = [NewData.name]

checkName函数后的产品

product.rows = [NewData.name="value of OldData.name", NewData.number="value of OldData.number"]

如何得到这个结果?

你的代码中有两件令人困惑的事情:

  • 您正在使用filteroutput数组的每个成员中执行操作。然而,过滤器应该用于……过滤那个数组,意思是不应该修改它,只返回它的一个子集。相反,您可能希望使用forEach。然而,考虑到下一个项目,可能你想使用map.
  • 正在修改传递给checkName函数的数组。这是令人困惑的,并可能导致难以发现的bug。相反,让你的函数"纯粹",这意味着它不应该改变它的输入,而只是返回你需要的数据。

我建议这样做:

checkName(output){
return output.map((NewData) => {
// find the old data item corresponding to the current NewData
const OldData = this.props.elements.find(x => x.key === NewData.key);

if (OldData) {
// If found, return a clone of the new data with the old data name

// This uses the spread syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
return {
...NewData, // Clone the NewData object
name: OldData.name, // set the value found in OldData.name in the "name" field of the cloned object
number: OldData.number, // You can do the same for each field for which you want to replace the value cloned from NewValue
};
} else {
// Otherwise, just return a clone of the NewData
return { ...NewData };
}
}
}

用法如下:

const named = this.checkName(product.rows)

注意,product.rows数组不会被修改!

可以获取旧对象的键和值。

const keys = Object.keys(oldObject);
const values = Object.values(oldObject);
// or
const [keys, values] = Object.entries(oldObject);

之后,你将用oldObject的所有键创建一个循环,并像数组一样插入newObject。

keys.forEach( (key, index) => newObject[key] = values[index]);
// or
for (const [key, value] of Object.entries(object1)) {
newObject[key] = value
}

像这样使用map

checkName(output){
return output.map(( NewData) =>{
this.props.elements.forEach((OldData) => {
if (NewData.key == OldData.key) {
NewData.name = OldData.name;
NewData.number = OldData.number;
}
})
return NewData;
})
// return output;
}

最新更新