将新值推送到对象数组,同时保持旧值不变React Js Next Js



我有一个带有图像名称的JSON文件。我想将数据存储在键值对象中。我正在使用regex创建密钥以删除-img[image No]。我无法将所有图像名称存储在数组中。当我添加一个新元素时,它会将其覆盖为以前的值。

如何在不擦除以前存储的数据的情况下在阵列中推送新数据?

数据文档

[
"apple-img1",
"apple-img2",
"apple-img3",
"apple-img4",
"apple-img5",
"dell-img1",
"dell-img2",
"dell-img3",
"hp-img1",
"hp-img2"
]

我的代码

content.map((contentInfo) => {
let key = contentInfo.replace(/-imgd$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
let imgName = contentInfo //Name of the Image

data[key] = {
Images: imgName //Append New Image 2 Array Instead of OverWriting Them
}
console.log(data);
})

电流输出

{
"apple": {
"Images": [
"apple-img5"
]
},
"dell": {
"Images": [
"dell-img3"
]
},
"hp": {
"Images": [ 
"hp-img2"
]
}
}

预期输出

{
"apple": {
"Images": [
"apple-img1",
"apple-img2",
"apple-img3",
"apple-img4",
"apple-img5"
]
},
"dell": {
"Images": [
"dell-img1",
"dell-img2",
"dell-img3"
]
},
"hp": {
"Images": [ 
"hp-img1",
"hp-img2"
]
}
}

Array.prototype.map()的输出将再次成为数组。在您的例子中,Array.prototype.reduce()是实现它的理想函数:

const data = [
"apple-img1",
"apple-img2",
"apple-img3",
"apple-img4",
"apple-img5",
"dell-img1",
"dell-img2",
"dell-img3",
"hp-img1",
"hp-img2",
];
const output = data.reduce((prev, curr) => {
// get the keyname
const [keyName] = curr.split("-");
if (prev[keyName]) {
// If the property exists then push to Images array
prev[keyName].Images.push(curr);
} else {
// If the property name does not exist,
// create it and add the initial value in the format you want
prev[keyName] = { Images: [curr] };
}
return prev;
}, {});
console.log(output);

您可以使用排列运算符来完成此任务

content.map((contentInfo) => {
let key = contentInfo.replace(/-imgd$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
let imgName = contentInfo //Name of the Image

data = {
Images: {...imgName, key} //Append New Image 2 Array Instead of OverWriting Them
}
console.log(data);
})

这应该行得通。

@Amila Senadhera提供的最佳解决方案。这种情况使用map函数的迭代来符合所需的输出对象。即使正在工作,也不会使用map函数的输出数组。

const content = [
"apple-img1",
"apple-img2",
"apple-img3",
"apple-img4",
"apple-img5",
"dell-img1",
"dell-img2",
"dell-img3",
"hp-img1",
"hp-img2"
]
let data = {}
content.map((contentInfo) => {
let key = contentInfo.replace(/-imgd$/, "") 
let imgName = contentInfo //Name of the Image
data[key] = {
Images: data[key] ? [...data[key].Images, imgName] : [imgName]  //Append New Image 2 Array Instead of OverWriting Them
}
})
console.log(data);

排列运算符可用于向数组添加值。

content.map((contentInfo) => {
let key = contentInfo.replace(/-imgd$/, ''); //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
let imgName = contentInfo; //Name of the Image
if (data[key] == undefined) {
data[key] = {
Images: [imgName],
};
} else {
data[key] = {
Images: [...data[key].Images, imgName], //Append New Image 2 Array Instead of OverWriting Them
};
}
console.log(data);
});