Find and update property of nested object javascript

Viewed 88

I have somewhere in theObject a property component and if this has the value "get-all", i want to add a property to this specific object.

async function getObject(theObject) {
  var result = null;
  if (theObject instanceof Array) {
    for (var i = 0; i < theObject.length; i++) {
      result = await getObject(theObject[i]);
      if (result) {
        break;
      }
    }
  }
  else {
    for (var prop in theObject) {
      if (prop == 'component') {
        if (theObject[prop] == "get-all") {

          theObject.stories = [ "some example stories"];
          return theObject
        }
      }
      if (theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
        result = await getObject(theObject[prop]);
        if (result) {
          break;
        }
      }
    }
  }
  return result;
}

Example Input

{
  "story": {
    "name": "Services",
    "content": {
      "_uid": "2b1dd39a-c9f1-4bf5-a90a-1129465edb2d",
      "body": [
        {
          "_uid": "85892460-cd4b-4bc9-8369-097b50b0839f",
          "color": {
            "_uid": "eefaa43d-7f9b-459d-b42d-fc16436dc085",
            "color": "",
            "plugin": "native-color-picker"
          },
          "style": "padding-top: 40px;\ntext-align: center;",
          "alignment": "center",
          "component": "h2",
        },
        {
          "_uid": "e3ef3c5f-391c-4be0-8b22-4f96d3dd542e",
          "slug": "technology",
          "component": "get-all",
        }
      ],
      "component": "page",
    },
    "slug": "services",
  }
}

Excpeteced Output

{
  "story": {
    "name": "Services",
    "content": {
      "_uid": "2b1dd39a-c9f1-4bf5-a90a-1129465edb2d",
      "body": [
        {
          "_uid": "85892460-cd4b-4bc9-8369-097b50b0839f",
          "color": {
            "_uid": "eefaa43d-7f9b-459d-b42d-fc16436dc085",
            "color": "",
            "plugin": "native-color-picker"
          },
          "style": "padding-top: 40px;\ntext-align: center;",
          "alignment": "center",
          "component": "h2",
        },
        {
          "_uid": "e3ef3c5f-391c-4be0-8b22-4f96d3dd542e",
          "slug": "technology",
          "component": "get-all",
          "stories": [...some example stories]
        }
      ],
      "component": "page",
    },
    "slug": "services",
  }
}
1 Answers

you don't need to async/await in your recursive function, also use Object.keys and forEach to loop through the objects something like this code

const getObject = (data) => {
    Object.keys(data).forEach((key) => {
    if (data[key] instanceof Object ) {
      return  getObject(data[key]);
    }
    if(key === 'component' && data[key] === 'get-all'){
      data['stories'] = ['some example stories']
    }
  });
  return  data;
};

 
console.log(getObject(data))
Related