让我们想象一下:
var fruits = [{ "Banana" : "yellow", "lemon" : "yellow"}, {"Orange" : "orange", "Mango" : "orange"}, {"Apple" : "red", "strawberry" : "red"}];
fruits.push({"Kiwi" : "green", "Green Apple" : "green", "watermelon" : "green" });
console.log(fruits);

现在我有一个数组"水果",内有对象,我正在使用" push()"添加新对象的方法。
如果我想添加一种新的黄色水果,例如"牙买加香蕉:黄色"在黄色物体里面,我怎么能这样做?
答案 0 :(得分:3)
你要做的事情不会很好。尝试这样的事情:
group by
答案 1 :(得分:2)
如果需要,您需要引用键和字符串值,但不要引用带有冒号的wole部分:Object initializer。
var fruits = [{ Banana: "yellow", lemon: "yellow" }, { Orange: "orange", Mango: "orange" }, { Apple: "red", strawberry: "red" }];
fruits.push({ Kiwi: "green", "Green Apple": "green", watermelon: "green"});
console.log(fruits);
答案 2 :(得分:2)
使用动态属性访问(括号表示法),不要忘记属性名称和其他水果对象中:
之间的引号:
var fruits = [{
"Banana": "yellow",
"Lemon": "yellow"
}, {
"Orange": "orange",
"Mango": "orange"
}, {
"Apple": "red",
"Strawberry": "red"
}]
fruits.push({
"Kiwi": "green",
"Green Apple": "green",
"Watermelon": "green"
})
fruits[0]["Jamaican Banana"] = "yellow"
console.log(fruits)
但是,我建议(比如Ryan和Mehul Mohan已经使用)在顶级fruits
对象中使用数组(换句话说,按颜色对数据进行排序):
var fruits = {
"yellow": ["Banana", "Lemon"],
"orange": ["Orange", "Mango"],
"red": ["Apple", "Strawberry"]
}
fruits["green"] = ["Kiwi", "Green Apple", "Watermelon"]
fruits["yellow"].push("Jamaican Banana")
console.log(fruits)
答案 3 :(得分:0)
var fruits = [{'Banana' :'yellow', 'lemon' : 'yellow'}, {'Orange' : 'orange', 'Mango' : 'orange'}, {'Apple' : 'red', 'strawberry' : 'red'}];
fruits.push({'Kiwi' : 'green', 'Green Apple' : 'green','watermelon' : 'green'});
console.log(fruits);