Into the depths we delve, extending beyond to an array of objects?

I have a question about the possibility of extending an array of objects like this:

Imagine I have :

 myObj = [
    {"name" : "one", "test" : ["1","2"]},
    {"name" : "two", "test" : ["1","2"]}
   ]

And I want to add to it something like -

 {"name" : "one" , "test" : ["1","3"]}

The expected result would be -

 myObj = [
    {"name" : "one", "test" : ["1","2", "3"]},
    {"name" : "two", "test" : ["1","2"]}
   ]

Essentially, if the object doesn't exist, it should be created. Is this type of operation possible? Appreciate any insights! Thanks!

Answer №1

Seems like you are looking for something similar to this:

function deepSetMerge(base, next) {
  var dataEntry = base.filter(function(it) {
    return it.name === next.name;
  })[0];

  if (dataEntry) {
    var diff = next.test.filter(function(it) {
      return dataEntry.test.indexOf(it) === -1;
    });
    dataEntry.test = dataEntry.test.concat(diff).sort();
  } else {
    base.push(next);
  }
}

var data = [{
  "name": "one",
  "test": ["1", "2"]
}, {
  "name": "two",
  "test": ["1", "2"]
}];

var add = {
  "name": "one",
  "test": ["1", "3"]
};

var obj = {
  "name": "totally-unique",
  "test": [1, 2, "nine", 17.0]
};

deepSetMerge(data, add);
deepSetMerge(data, obj);

document.getElementById('results').textContent = JSON.stringify(data);
<pre id="results"></pre>

This approach involves searching for an existing entry by name in the data structure. If no match is found, it adds the new object as a new entry.

If the entry exists, it compares the sets of items and appends any unique elements to the existing array (and sorts them).

While tailored to your specific data format, this solution effectively demonstrates the algorithm at play.

Answer №2

Creating a universal extend implementation can be quite complex and expensive. This is why extensive explorations are typically avoided. It's more efficient to understand your data model and customize your approach accordingly.

Based on the given example, I would make certain assumptions about the data model:

  1. Each object will have a unique name property that can be used for searching.
  2. The test property holds an array (which simplifies the process, though it could also be an object requiring a standard extend implementation).

In this scenario, you could tackle it in the following manner:

var myObj = [
  {name: 'one', test: ['1', '2']},
  {name: 'two', test: ['1', '2']}
];

function extendTestValue(data, value) {
  var names = data.map(function(item) {
    return item.name;
  });
  var index = names.indexOf(value.name);
  if (index < 0) {
    data.push(value);
  } else {
    value.test.forEach(function(item) {
      if (data[index].test.indexOf(item) < 0) {
        data[index].test.push(item);
      }
    });
  }
  return 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

JavaScript function unable to execute form action properly

I have a link RESET YEAR which triggers a servlet to check if the current year is equal to the present year. If they are not equal, then the function resetyear() is supposed to be called. The issue I am facing is that the function is not working as expecte ...

Unexplained quirks observed in AngularJS $watch during the initialization of a controller

I am working with a code snippet that utilizes AngularJS: var app = angular.module('Demo', []); app.controller('DemoCtrl', function ($scope) { function notify(newValue, oldValue) { console.log('%s => %s', oldValue, ...

Extracting a specific variable value from a response by sending a request with CURL command and manipulating the data using JavaScript

Here is my Curl request: curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \ -X GET "https://api-cloud.browserstack.com/app-automate/sessions/22dbfb187486090d974a11ac91t65722988e0705.json" This is the Response I received: { "automati ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

JavaScript code failed to run

I am currently attempting to invoke a JavaScript script to export a chart from the PrimeFaces chart component. The issue I am facing is that the base64str variable appears to be null, and the script responsible for populating this value is not being called ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

The Challenge with jQuery Radio Buttons

I am currently using jQuery to toggle the visibility of a div element. However, I am facing an issue where the else condition is being executed even when it should not be. I am unsure of what mistake I may have made in my code. Any help would be greatly ap ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

How to transmit data using ajax through a hyperlink? (Without relying on ExtJS, jQuery, or any other similar libraries)

I have a link that says "follow me" and I want to send some basic data to the page without having it reload. Update: I just realized that using "onclick" will help me achieve what I need. Got it. Update 2: I mean, something like this: follow me ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Issue: The THREE.GLTFLoader cannot process this asset. Only glTF versions below 2.0 are compatible

Upon utilizing three.js, I encountered an error while parsing data from the GLTF JSON file. This file was exported from the three.js 3D viewer and editor, indicating a version of 4.5 in the JSON content. Highlighted below is the JSX code snippet: import { ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

What could be causing my Leaflet popup to suddenly close?

My feature allows users to search for a marker and zoom to its location, triggering the popup to open. Everything is functioning correctly, except that the popup closes after the function executes. I am struggling to pinpoint what is causing the popup to c ...

Tips for transferring the id from a delete button to a delete button in a popup dialog box

In my frontend application, there is a table where each row corresponds to an item. For every row, there is a "Remove" button that triggers a warning popup upon being clicked. The intention is to pass the item's ID in this popup so that if the user co ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

AngularJS - let's make pagination more interactive by adding an active class to the current page

Check out this fiddle I created: http://jsfiddle.net/tbuchanan/eqtxLkbg/4/ Everything is working as intended, but I'm looking to add an active class to the current page when navigating through the pages: <ul class="pagination-controle pagination" ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...