Skip to content
Advertisement

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

Let’s suppose I have an API response that looks like this:

const data = {
  users: [
    { name: "John", teams: [{ name: "Liverpool" }] },
    { name: "Sam", teams: [{ name: "MC" }, { name: "United" }] },
  ],
  photos: [
    { id: "123", types: ["JPG", "PNG"], comments: [{ description: "sample photo" }] },
  ],
};

I want to transform it by adding the rid property to each object.

const data = {
  rid: "ABC",
  users: [
    { rid: "ABC", name: "John", teams: [{ rid: "ABC", name: "Liverpool" }] },
    { rid: "ABC", name: "Sam", teams: [{ rid: "ABC", name: "MC" }, { rid: "ABC", name: "United" }] },
  ],
  photos: [
    { rid: "ABC", id: "123", types: ["JPG", "PNG"], comments: [{ rid: "ABC", description: "sample photo" }] },
  ],
};

How can I do so? I think there is some kind of recursion involved but I haven’t been able to draft a solution?

Thanks.

Advertisement

Answer

You just need to iterate through object with recursive function.

Try below snippet.

const data = {
  users: [
    { name: 'John', teams: [{ name: 'Liverpool' }] },
    { name: 'Sam', teams: [{ name: 'MC' }, { name: 'United' }] },
  ],
  photos: [
    { id: '123', types: ['JPG', 'PNG'], comments: [{ description: 'sample photo' }] },
    { key: null }, // Fixed null values
  ],
}

function addProperty(obj, key, val) {
  if (!obj || typeof obj !== 'object') return
  if (!Array.isArray(obj)) obj[key] = val
  Object.values(obj).forEach((obj) => addProperty(obj, key, val))
}

addProperty(data, 'rid', 'ABC')

console.log(data)
Advertisement