-1

Good day,

So I'm trying to insert an object to my single javascript json object.

I have this sample result which is called fruits when I enter the value inside console.log(JSON.stringify(fruits))

{"Apple": {"price": 100}, "Banana": {"price": 120}, "Grapefruit": {"price": 300}}  

But I need to push or append new fruit which is the Mango in this result.

What I tried so far is something like this.

fruits.push({"Mango": {"price":350})
console.log(fruits)

But apparently, I'm getting an error.

Any help?

hik hyper
  • 97
  • 5
  • Objects do not have a push method. Consider using either the square bracket notation? `fruits["Mango"] = {"price":350}`? – evolutionxbox Jan 18 '21 at 10:46
  • Does this answer your question? [how to add key value pair in the JSON object already declared](https://stackoverflow.com/questions/28527712/how-to-add-key-value-pair-in-the-json-object-already-declared) – costaparas Jan 18 '21 at 12:06

3 Answers3

2

Your data is stored in an javascript object as property. To add new property to fruits, try this:

fruits["Mango"] = { price : 350 };
esertbas
  • 476
  • 3
  • 7
1

You can use ... spread operator.

fruits = {...fruits, "Mango": {"price":350}}
mark333...333...333
  • 1,270
  • 1
  • 11
  • 26
0

assign() is used to copy objects to a target object

Object.assign(fruits,{"Mango" :{ "price" : 350} });
anju
  • 589
  • 12
  • 25