You’ll learn how to push JSON object into an array using JavaScript. You can make use of Array.push method to push a JSON object to an array list.
let list = [];
let myJson = {
"name" : "sam"
}
list.push(myJson);
console.log(list)
Let’s look at another use case where you have to create a JSON object dynamically from an array and push to another array.
let list = [];
let input = ["John","Hari","James"]
let myJson;
for(let i = 0; i < input.length; i++){
myJson = {"name" : input[i]};
list.push(myJson);
}
console.log(list)
Now instead of using a for loop you can also use JavaScript reduce method to create a new JSON object array dynamically.
let list = [];
let input = ["John","Hari","James"]
let myJson;
list = input.reduce((accumulator, currentValue, index, array) => {
accumulator.push({"name" : currentValue});
return accumulator;
},[])
console.log(list)