Steps for adding an object to an existing array of objects in a JSON format

My JSON object is dynamic and structured like the following,

let data_existing= [
       {
          "client":[
             {
                "name":"aaaa",
                "filter":{
                   "name":"123456"
                }
             }
          ]
       },
       {
          "server":[
             {
                "name":"qqqqq",
                "filter":{
                   "name":"984567"
                }
             }
          ]
       },
               ]

When I receive input, it looks like this,

let data_new =  {
      "client":[
         {
            "name":"bbbbb",
            "filter":{
               "name":"456789"
            }
         }
      ]
    }

I want to add this new object into the existing "client" JSON object. The expected output should be,

[
   {
      "client":[
         {
            "name":"aaaa",
            "filter":{
               "name":"123456"
            }
         },
         {
            "name":"bbbb",
            "filter":{
               "name":"456789"
            }
         }
      ]
   },
   {
      "server":[
         {
            "name":"qqqqq",
            "filter":{
               "name":"984567"
            }
         }
      ]
   }
]

If the "data_new" object does not exist in the main objects, it should be added as a new object like so,

 let data_new =  {
          "server2":[
             {
                "name":"kkkkk",
                "filter":{
                   "name":"111111"
                }
             }
          ]
        }

The output will look like,
[
   {
      "client":[
         {
            "name":"aaaa",
            "filter":{
               "name":"123456"
            }
         },
      ]
   },
   {
      "server":[
         {
            "name":"qqqqq",
            "filter":{
               "name":"984567"
            }
         }
      ]
   },
{
      "server2":[
         {
            "name":"kkkkk",
            "filter":{
               "name":"11111"
            }
         }
      ]
   }
]

I have attempted the method below, but it did not work as expected. Any help would be greatly appreciated.

This is what I tried, but it did not produce the expected result,

function addData(oldData, newData) {
  let [key, value] = Object.entries(newData)[0]
  return oldData.reduce((op, inp) => {
    if (inp.hasOwnProperty(key)) {
    console.log("111");
      op[key] = inp[key].concat(newData[key]);
    } else {
    console.log(JSON.stringify(inp));
      op = Object.assign(op, inp);
    }
    return op
  }, {})
}

Answer №1

Your code works well when the key is already present in the data_existing object (e.g.: "client").

However, you also need to consider the scenario where the key is not found in any of the objects within data_existing (e.g.: "server2").
To handle this, you should check for the absence of the key after the reduce loop and add the new item to data_existing if it was not found.

Below is an example implementation to accomplish that:

function updateData(inputData, newItem) {
  const [newKey, newValue] = Object.entries(newItem)[0];

  let keyFound = false; // flag indicating if key was found
  const result = inputData.reduce((accumulator, item) => {
    const [key, value] = Object.entries(item)[0];
    if (key === newKey) {
      keyFound = true;
    }
    const updatedItem = { [key]: key === newKey ? [...value, ...newValue] : value };
    return [...accumulator, updatedItem];
  }, []);

  if (!keyFound) {
    result.push(newItem); // add new item if key not found previously
  }
  return result;
}

I hope this solution is helpful for your needs.

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

Preview functionality is disabled in the iOS share extension

Currently, I'm developing a share extension for Safari on iOS. Our approach involves utilizing the default UI provided by iOS and extending the SLComposeServiceViewController class. In addition to this, I have incorporated a JavaScript function to ext ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

Concealing specific DIV elements (unfortunately not nested)

Currently, I am dealing with pre-existing code that is automatically generated and needs to adhere to a specific format: <div id="TITLE1"></div> <div id="div-1"></div> <div id="div-2"></div> <div id="div-3"></d ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Transform JSON keys into separate columns with predetermined titles in Pandas

Seeking a way to expand dataframe from JSON data with predefined values. The goal is to gather all the key values from the JSON data and use them as column headers. id |Name | MonthWise 0 |ABC |{'102022':{'val':100, 'count&a ...

Using router-links with events: A simple guide

My current issue involves passing information to another page. During testing without using routes, I was successful in passing information from one component to another. However, after implementing routes, clicking the event navigates to the other compo ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

The data does not seem to be getting sent by the res.send() method in

I'm having trouble with the GET request not returning the data I expect. Here is my GET request code: router.get('/', (req, res) => { res.set('Content-Type', 'text/html') res.status(200).send(Buffer.from('<p& ...

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

JavaScript code that transforms a comma-separated string of words into key-value pairs within an array

I am looking to transform a list of email addresses into a key-value object within an array. Starting with "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40252d21292c002d21292c6e232f2d">[email protected]</a> ...

Strategies for setting up the runtime dynamically for Nextjs API routes

After deploying my Next.js 13 app on Cloudflare Pages, I encountered an issue with the API routes. To address this, I had to export the runtime variable from each route in the following manner. export const runtime = "edge" During local developm ...

Implementing JSONResponse retrieval in Django from a separate views module

In the views directory, I have two files: /views/api.py and /views/pages.py /views/api.py contains methods that return JSONResponse objects. For example: @api_view(['GET']) def foos(request): foos = get_list_or_404(Foo) data = [{' ...

Press the submit button after receiving the ajax response

Is there a way to manually or programmatically submit a specific page? The catch is that before the submission can happen, a function called create_impi_num(x) needs to be triggered in order to store data using $.post(). The issue at hand: If I set the s ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

A guide on shading specific faces based on their normal vectors' alignment with the camera's view

https://i.sstatic.net/FG4hp.png I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly? uniform float tim ...

There was an error in the search: [parse_exception] The search source could not be parsed. A field name was expected, but instead [

I'm experiencing a query parsing exception while utilizing JavaScript for Elasticsearch configuration found in elastic.js file. Results are obtained when the filtered part is removed. However, upon adding it back, an exception occurs. var client = r ...