我有这个代码,我添加了两个评论(带有ID和NAME):
var data = {
SKU: 'CS4',
Name: 'Dell Laptop Inspiron 41',
Quantity: 1,
ItemPrice: 121,
"Reviews" : [
{
"ID": 2551,
"Name": 'john',
},
{
"ID": 255551,
"Name": 'j5ohn',
}
};
如何动态添加它们(我将使用ajax从其他网站获取评论数据)?
我试过这些代码,但我不知道为什么它不起作用而且我完全迷失了。
var data = [{
SKU: 'CS4',
Name: 'Dell Laptop Inspiron 41',
Quantity: 1,
ItemPrice: 121,
}];
var total_reviews = 5;
for (i=1; i<=total_reviews; i++) {
Object.assign(data.Reviews, { "ID": data.from.other.sites.ID, "Name": data.from.other.sites.NAME });
}
你能告诉我哪些部分我不知道了吗?或者你可以给我提示或代码让我开始吗?
答案 0 :(得分:1)
data[0].Reviews = []
for (i=1; i<=total_reviews; i++) {
data[0].Reviews.push({ "ID": data.from.other.sites.ID, "Name": data.from.other.sites.NAME })
}
答案 1 :(得分:0)
在示例输出中,对象的Reviews
属性是一个对象数组。这个简单的代码可以帮助你做到这一点:
var data = [
{
SKU: 'CS4',
Name: 'Dell Laptop Inspiron 41',
Quantity: 1,
ItemPrice: 121
}
];
var total_reviews = 5;
for (var i = 1; i <= total_reviews; i++) {
// This doesn't work because you are trying to push it to an Array.
// Object.assign(data.Reviews, { "ID": data.from.other.sites.ID, "Name": data.from.other.sites.NAME });
// First make sure that the array is initialized.
data[0].Reviews = data[0].Reviews || [];
// Then add the object to your array.
data[0].Reviews.push({
"ID": "data.from.other.sites.ID",
"NAME": "data.from.other.sites.NAME"
});
}
答案 2 :(得分:0)
这应该让你朝着正确的方向前进:
if(!data.Reviews){
data.Reviews = []
}
review = {"ID": "someId", "Name": "someName"}
data.Reviews.push(review)
答案 3 :(得分:0)
您的数据对象似乎不是普通对象。 这是一个数组。
因此,如果要将新评论添加到该数组的元素中,请按其键(唯一标识符)查找元素,并将新评论推送到元素“评论”属性中。
const index = data.indexOf(element => element.id === id);
if (index !== -1) {
for (let i = 0; i < total_reviews; i++) {
data[index]['Reviews'].push({ "ID": data.from.other.sites.ID, "Name": data.from.other.sites.NAME };
}
}
答案 4 :(得分:0)
请检查:
var data = {
SKU: 'CS4',
Name: 'Dell Laptop Inspiron 41',
Quantity: 1,
ItemPrice: 121,
"Reviews" : [
{
"ID": 2551,
"Name": 'john',
},
{
"ID": 255551,
"Name": 'j5ohn',
}]
};
var total_reviews = 5;
for (i=1; i<=total_reviews; i++) {
data.Reviews.push({ "ID": 'id_'+i, "Name": 'name_'+i })
}
console.log(data.Reviews);