Locate and modify a nested object property in JavaScript

There is a specific property component within the object, and if its value is "get-all", I want to append another property to this particular 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",
  }
}

Expected 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",
  }
}

Answer №1

Make sure to incorporate Object.keys and forEach in your recursive function instead of using async/await. Here is an example code snippet showcasing this approach:

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

 
console.log(retrieveObject(data))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Debug in Webstorm 7.0.3 by smoothly switching out Node.js files

Recently, I've embarked on a journey with Node.js and Webstorm 7.0.3. After creating a basic Node.js app using express and running it locally, I encountered an issue: I couldn't seem to make changes in a .js file, save it, refresh the browser, an ...

An issue has occurred: TypeError - It is impossible to access the 'forEach' property of an undefined object

Having trouble with a promise issue that I just can't seem to solve. Whenever I enter 'pizza' into the search bar and click search, the console displays an error message: TypeError: Cannot read property 'forEach' of undefined I&ap ...

Extract the property value and save it as an array in Vue

Looking to extract all values of a specific property and save them as an array. I attempted the following method: data() { return { roomList: null } }, methods: { getRooms() { var that = this axios.get('http://local ...

Toggle the on and off functionality of a button using ajax response for content display

I'm struggling to figure out why the button isn't working for me. I am familiar with how to enable and disable buttons using attr and prop. $(document).on("click", "#btn", function(){ $(this).html("Sending..."); $(this).prop("disabl ...

Including a unicode escape sequence in a variable string value

I'm struggling to find the right way to include a unicode escape in a dynamic string value to display emojis in React. My database stores the hexcode for the emoji (1f44d) I have set up a styled-component with the necessary css for rendering an emoj ...

Angular failing to reflect changes in my select element according to the model

One issue I'm facing in my application is with grouped select elements that share the same options. Whenever one select element changes, it checks the others to see if the new option selected has already been chosen in any of the other selects. In suc ...

Unable to modify the 'src' attribute of an Iframe using JavaScript

I've been working on a project using coinhive, but I encountered some difficulties. My initial goal was to display a webpage in an iframe while coinhive mined (don't worry, I'm only using it for personal purposes and not for anything illega ...

Is a directive necessary for a search element in this component?

I am currently learning angularJS and although it would be simpler to use JQuery for this task, I am determined to do it the right way. Essentially, I want to create a text input field where users can type in a search term, press a search button, and then ...

Retrieving POST request headers in Nightmare JS following a click() function execution and a wait() function delay

When I navigate a page, I input something in a field using type(), click on a button with click(), and then wait for an element to appear using wait(). I am interested in retrieving all the headers associated with the POST request that is triggered after ...

Tips for positioning the Google Custom Search bar

I am looking to position the Google custom search box on the left side of my website. Currently, I am using a website builder called imxprs and have implemented this code for my custom search box. <script> (function() { var cx = '013012 ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template> <article class="message is-warning"> <div class="message-header"> <span>Code Examples</span> </div> <div class="message-body"> ...

"Ensuring Contact Information is Unique: A Guide to Checking for Existing Email or Phone Numbers in

I'm encountering an issue with validating email and phone numbers in my MongoDB database. Currently, my code only checks for the presence of the email but does not respond to the phone number. const express = require("express"); const router ...

Exploring key value pairs dynamically in JavaScript

I have a JSON object containing HTTP request information: "http": { "method": "POST", "headers": [{ "content-type": "application/json" }, { "Authorization": "KKYZASSHUYTRJ" }], "url": "http://localhost:8888/download/con ...

Reactiveness issue with Vue JS: Javascript module variables not updating

After creating a validator module inspired by vee-validate, I wanted to use it in combination with the composition api. However, I encountered an issue where the errorMessages stored in a reactive array were not updating in the Vue template despite being s ...

React checkbox displaying incorrect render

I'm currently working on developing a React component that acts as a tile representation. This particular component consists of a div containing a label and a checkbox. The issue I'm facing is that I can click anywhere on the component to trigg ...

Develop an Innovative Data-Driven Application using AJAX Technology

After inputting an artist's name and clicking on the button, I expect to receive a visually appealing list of their songs. I am encountering the following issue: Whenever I hit the button, no results are being returned, and I am unsure of the reaso ...

Generate a graph by utilizing $getJSON and ChartJS

I am currently working on creating a bar chart using ChartJS and a JSON file. The data format is provided below, with each object containing information about the station name and arrival time. My goal is to populate an array where the x-axis represents St ...

Exploring jQuery functionality through data attributes

I'm having trouble implementing the search functionality using the data-find attribute. Currently, my function is simply matching the input string with any text inside the container. You can test this by adding more words to the HTML and then enterin ...