I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example:
config = {
existing_value: 'sample'
}
addToListing = (field, value, index=0) => {
config = {
...config,
listing: {
...config.listing,
[field]: value
}
}
}
addToListing('first', 1, 0)
addToListing('second', 2, 0)
addToListing('first', 3, 1)
console.log(config)
Result:
{
existing_value: 'sample',
listing:
{
first: 3,
second: 2
}
}
Desired outcome:
{
existing_variable: 'example',
listing:
[
{first: 1, second: 2},
{first: 3}
]
}
I have attempted various methods but I couldn't achieve the expected result (like using nested values or initializing at the beginning).
Can anyone provide assistance?