"Implement a function in Node.js/JavaScript that creates a new JSON object if the ID matches with the ID of another

const data = [
    {
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        content: { type: { name: "Author" } },
      },
      DataDetails: {
        shortSlugOption: { "en-us": "some value", "za-op": "random value" },
        mediaFileAssetLink: { "en-us": "some file", "za-op": "file Linl" },
        mediaFileAssetGalary: { hi: "file link 2" },
        singleMediaImage: { hi: "file link single", "en-us": "english link" },
        gallery: {
          "za-op": [
            {
              conf: {
                type: "media",
                id: "01",
              },
            },
            {
              conf: {
                type: "media",
                id: "10",
              },
            },
          ],
        },
        mediaAccess: {
          hi: {
            conf: {
              type: "media",
              id: "01",
            },
          }, 
          en: {
            conf: {
              type: "media",
              id: "1000",
            },
          },
        },
      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        content: { type: { name: "Author" } },
      },
      DataDetails: {
        short: { "en-us": ["shorts", "values"], "za-op": "short details" },
        shortSlugOption: { "hi-In": "options" },
        booleanField: { "hi-In": "true" },
        entryDetails: {
          "hi-In": [
            {
              conf: {
                type: "entry",
                id: "100",
              },
            },
            {
              conf: {
                type: "entry",
                id: "34",
              },
            },
          ],
        },
        singleEntry: {
          "en-us": {
            conf: {
              type: "entry",
              id: "34",
            },
          },
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        content: { type: { name: "testing" } },
      },
      DataDetails: { testingNewValue: { "en-us": "details value" } },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        content: { type: { name: "new" } },
      },
      DataDetails: {
        oneReference: { hi: "values 1" },
        multiReference: { "hi-In": "values 2" },
        media: {
          hi: {
            conf: {
              type: "media",
              id: "01",
            },
          },
        },
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        content: { type: { name: "new" } },
      },
      DataDetails: { testingNewValue: { "hi-IN": "jksdsdo" } },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        content: { type: { name: "testing" } },
      },
      DataDetails: { testingNewValue: { "en-us": "kknksdo" } },
    },
    {
      system: {
        id: "2OspeCtNK0sh2cPiuU9jIz",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        short: { "za-op": "dfvndkssa" },
        shortSlugOption: { hi: "sdocjosmdc" },
        mediaFileAssetLink: { "en-us": "jdsojocis" },
        booleanField: { "hi-In": "true" },
      },
    },
    {
      system: {
        id: "2eAmIIuG4xkLvatkU3RUSy",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        dummy: { "en-us": "dshcifdvk" },
        india: { "za-op": "sdci", hi: "hewd" },
      },
    },
    {
      system: {
        id: "7hbdS3MgfZ73TOtlu1WfXw",
        type: "Entry",
        content: { type: { name: "dummy" } },
      },
      DataDetails: {
        testingNewValue: { "en-us": "sdcoklsdc" },
        locationField: { hi: "sdcndkdc" },
      },
    },
  ],
  result = data.reduce(
    (
      r,
      {
        system: {
          id,
          content: {
            type: { name },
          },
        },
        DataDetails,
      }
    ) => {
      r[name] ??= {};
      Object.entries(DataDetails).forEach(([key, object]) => {
        Object.entries(object).forEach(([loc, value]) => {
          r[name][loc] ??= {};
          r[name][loc][id] ??= {};
          if (typeof value !== "object") {
            r[name][loc][id][key] = value;
          } else {
            console.log(value);
          }
        });
      });
      return r;
    },
    {}
  );

console.log(result)

In the above output I am trying to replace the media with the below object as the below code is for the media I want to match the id which is present inside the data output and replace the json with the mediaObj matching id

let mediaObj = {
  "01": {
    status: true,
    tag: [],
    filename: "exute-image.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "02": {
    status: true,
    tag: [],
    filename: "wallpapers-6.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "10": {
    status: true,
    tag: [],
    filename: "in-space-rk.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "25": {
    status: true,
    tag: [],
    filename: "justice-league.jpg",
    is_dir: false,
    parent_uid: null,
  },
  "67": {
    status: true,
    tag: [],
    filename: "batman.jpg",
    is_dir: false,
    parent_uid: null,
  },
};

so my expected output is like this when I run my program

Expected Value

{
  "Author": {
    "en-us": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "shortSlugOption": "some value",
        "mediaFileAssetLink": "some file",
        "singleMediaImage": "english link"
      },
      "1aBOO8tu3lUsjtICuIbUM5": {}
    },
    "za-op": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "shortSlugOption": "random value",
        "mediaFileAssetLink": "file Linl"
      },
      "1aBOO8tu3lUsjtICuIbUM5": {
        "short": "short details",
        "gallery": [
          {
            "status": true,
            "tag": [],
            "filename": "exute-image.jpg",
            "is_dir": false,
            "parent_uid": null
          },
          {
            "status": true,
            "tag": [],
            "filename": "in-space-rk.jpg",
            "is_dir": false,
            "parent_uid": null
          }
        ]
      }
    },
    "hi": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "mediaFileAssetGalary": "file link 2",
        "singleMediaImage": "file link single",
        "mediaAccess": [
          {
            "status": true,
            "tag": [],
            "filename": "exute-image.jpg",
            "is_dir": false,
            "parent_uid": null
          }
        ]
      }
    },
    "hi-In": {
      "1aBOO8tu3lUsjtICuIbUM5": {
        "shortSlugOption": "options",
        "booleanField": "true"
      }
    }
  }
}

as the id get changed and I want to match every-time with the mediaObj json and replace the value if there is multiple or single media file exits but if the media id does not match with mediaObj then it should delete the that json as you can see in mediaAccess id 1000 does not match with the mediaObj so it should delete it

as the same applies with the entries if I get the media replace code then I can try with the entry code too

Answer №1

It seems like the solution you're searching for is right here:

Substitute

          } else {
            console.log(value);
          }

with this:

        } else {
          const updatedValues = Array.isArray(value) ? value.map(replacePossibleConf) : [ replacePossibleConf(value) ];
          if (updatedValues.filter(result => result != null).length > 0) {
            r[name][loc][id][key] = updatedValues;
          }
        }

and insert this function:

function replacePossibleConf(possibleConf) {
  return mediaObj[possibleConf?.conf?.id];
}

This will provide an outcome that closely aligns with your original query:

{
  "Author": {
    "en-us": {
      "4gSSbjCFEorYXqrgDIP2FA": {
        "shortSlugOption": "some value",
        "mediaFileAssetLink": "some file",
        "singleMediaImage": "english link"
      },
      "1aBOO8tu3lUsjtICuIbUM5": {}
    },
   ...
    ...
    ...
    }
  }
}

Answer №2

Hey there, it seems like your question is a bit convoluted but I'll do my best to help you out. If you're working with JSON data, you'll need to convert it into a JavaScript object in order to extract the information you need.

let parsedData = JSON.parse(JSON.stringify(data))

By doing this, you can easily access and manipulate the keys and values within the data you've received. Next, consider creating a constructor function that takes in both the parsed data object and the new data you want to replace within it:

const constructNewData = (parsedData, replaceData) => {
    let newData = {};
    Object.keys(parsedData).forEach(key => {
        if (replaceData[key]) {
            newData[key] = replaceData[key];
        } else {
            newData[key] = parsedData[key];
        }
    });
    return newData;
}

This function will allow you to iterate over the keys of your original data and replace the values as needed. Feel free to provide more specific details about which values you're looking to replace so I can assist you further :)

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

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Having Trouble with Bcrypt Saving Your Password?

Having trouble with saving a new password to the database when hashing it? I am utilizing MongoDB, NodeJS, and Passport for allowing users to change their passwords. UserSchema.pre('save', function(next) { var user = this; var SALT_FACTOR = ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

Why is it that consolidating all my jQuery plugins into one file is ineffective?

Prior to this, I included the following scripts: <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/json2.js"></script> <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/jquery-msdropdown/js/jquery.dd.js"></script&g ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

The placement of Bootstrap Datepicker is experiencing issues

I have integrated the Bootstrap Datepicker from Eternicode into my ASP.Net MVC website. While the functionality is working well, I am facing difficulty in positioning the datepicker modal using the orientation option mentioned in the documentation and code ...

Customizing file names in sails using req.file('file')

Currently, I am working on sails and have been able to successfully upload a file from the client to the server without using a form. I am utilizing fs.createReadStream('file') for this purpose. The file data is sent to the server and everything ...

Retrieve the chosen selection from a dropdown menu using AngularJS and Ionic

I've been encountering some issues with the select feature in AngularJS. Despite searching extensively for solutions, none seem to be working for me. The JSON structure I'm dealing with is generated from my service.php: [ { "Name": ...

Issue with authentication persistence between React frontend and Node.js backend causing passport not to persist user credentials

I have implemented a Node.js and express backend along with a React frontend. Currently, I am using Passport.js with the Local Authentication Strategy. The issue arises when I log in on my React login component; it works perfectly in the Node.js app.post(" ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

`Save user edits on the webpage using Electron`

I am encountering an issue with my electron app. I use the window.loadUrl() method to navigate between pages. Some of these pages require users to input data that needs to be saved. The problem arises when a user enters information, moves to another page ...

Saving the object returned by the useRef hook into the Redux state

I have a question. I am developing a music platform similar to Spotify using Next.js. To manage states, I am utilizing Redux Toolkit. In order to play music, I have integrated the audio element within a component that includes controls to adjust the music ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...