Nested Json: How to Add (Push) New Items to an Object

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

Push new object to nested object

This is mutable solution - we first index all object to idHash map which contains info about object id, object index in data array, and dara array itself (parentArr) - and ten we find object id=3 and isert new after it.

let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}
let makeHash = data => (data||[]).forEach((d,i)=>
(idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));

makeHash(mainConatiners);

let hobj = idHash[3] // hash object with object id=3 after which we want to insert
hobj.parentArr.splice(hobj.index+1,0,newObj);

mainConatiners = [{  page_title: "This is first page.",  "data": [{      id: 1,      title: "This is first question",      type: 1,      page: 0,      position: '0',      parent: '0'    },    {      id: 2,      title: "This is second question",      type: 2,      page: 0,      position: '1',      parent: 0,      "data": [{          key: "[data][1][data][0]",          id: 3,          title: "This is third question",          type: 1,          page: 0,          position: '1-0',          parent: 2        },        {          id: 4,          title: "This is fourth question",          type: 2,          page: 0,          position: '1-1',          parent: 2,          "data": [{            id: 5,            title: "This is tenth question",            type: 2,            page: 0,            position: '1-1-0',            parent: '2-4'          }]        }      ]    }  ]}]
let newObj = { key: "[data][1][data][0]", id: 12, title: "This is third question", type: 1, page: 0, position: '1-0', parent: 2}
let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}let makeHash = data => (data||[]).forEach((d,i)=> (idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));
makeHash(mainConatiners);
let hobj = idHash[3] // hash object with object id=3 after which we want to inserthobj.parentArr.splice(hobj.index+1,0,newObj);
console.log(mainConatiners)

TypeScript: Push to an array of Nested JSON Object

First of all, I think that the last two examples of expected output do not define a correct key. Since the inputs are arrays at their top level, and you expect the first array value to be replaced, you should have 0 as the first entry in the key.

In the code I see two issues and have a few more remarks:

  1. In case keys is the empty array, and the data is not an array, it should be replaced by the new value, so instead of return json, you should return value

  2. When coming back from the recursive call, and the current level is an array, the new value should not be appended to the array, but instead be the replacement value for what was at indexKey.

  3. Not a real problem, but I would not mutate keys.

  4. Not a problem with the algorithm, but the name json in your property and variable names is not appropriate. JSON is something you would have to pass to JSON.parse. Anything else should not be called JSON.

This results in the following adapted code:

const addNested = (
data: Record<string, any> | any[],
value: any,
keys: string[]
): Record<string, any> | any[] => {
const isArray = Array.isArray(data);
if (keys.length === 0) {
if (isArray) {
return [...data, value];
}
return value; // Overwrite any data
}
// Don't mutate keys with shift
const key = keys[0] as string;
const indexKey = +key || 0;
const newData = isArray ? data[indexKey] : data[key];
const nestedValue = addNested(newData, value, keys.slice(1));
return isArray
? Object.assign([], data, { [indexKey]: nestedValue }) // Replace at index
: { ...data, [key]: nestedValue };
}

const addNested = (
data /*: Record<string, any> | any[] */,
value /*: any */,
keys /*: string[] */
) /*: Record<string, any> | any[] */ => {
const isArray = Array.isArray(data);
if (keys.length === 0) {
if (isArray) {
return [...data, value];
}
return value; // Overwrite any data
}
// Don't mutate keys with shift
const key = keys[0] /* as string */;
const indexKey = +key || 0;
const newData = isArray ? data[indexKey] : data[key];
const nestedValue = addNested(newData, value, keys.slice(1));
return isArray
? Object.assign([], data, { [indexKey]: nestedValue }) // Replace at index
: { ...data, [key]: nestedValue };
}

console.log(addNested([], 1, [])); // [1]
console.log(addNested([{a: {b:[]}}], 1, [0,'a','b'])); // [{a:{b:[1]}}]
console.log(addNested([{a: {b:[{c:[4]}]}}], 1, [0,'a','b','0','c'])); // [{a: {b:[{c:[4,1]}]}}]

javascript adding items to json object using a nested array

In order to use a variable as a key to an object you need to enclose it in [], try using this let feed = {[names[j]] : getData(data[i])};

Add nested json object item to another json item

You can use push() with the spread operator or concat and reassign:

var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
JSON1[0].activityLogs.push(...JSON2[0].activityLogs)
console.log(JSON1)

Push nested JSON values to array

Try this

var a={"team" : [   {    "paid": {        "refugee": 2018,          "local": 29000,           "international": 12000    }},
{ "unpaid": { "refugee": 2019, "local": 39000, "international": 19000 }}]}var refugee=[];var local=[];var international=[];a.team.map((e)=>{ if(e.paid) {refugee.push(e.paid.refugee);local.push(e.paid.local);international.push(e.paid.international) } else { refugee.push(e.unpaid.refugee);local.push(e.unpaid.local);international.push(e.unpaid.international) }
})console.log(local)console.log(international)console.log(refugee)

JSON push to nested JSON object in javascript

I observed one thing in your code at:

var tempActEffort =[];
tempActEffort = actEffortData[k].effort;

Here, you declared a variable 'tempActEffort' as an array.Then you are directly initializing some value as 'tempActEffort = actEffortData[k].effort' to it so that its type got changed from array to resulting type. So, then push is not a function defined on it as it is not an array type at the moment.

So, instead of assigning value as 'tempActEffort = actEffortData[k].effort' change it as:

tempActEffort.push(actEffortData[k].effort);

How to add a property to every object in a nested JSON structure in JavaScript?

You just need to iterate through object with recursive function.

Try below snippet.