Verify if a certain attribute of an entity is present before making modifications to a different attribute

I currently have an array containing objects structured like this:

    let arr = [
        { taxonomy: 'category', id: [ 10, 100 ] },
        { taxonomy: 'post_tag', id: [ 20 ] },
    ];

My goal is to insert a new object into the array with the following structure:

    const object = {
        taxonomy: 'category',
        id: 30
    }

I am looking for a solution to check if an object with the property value of 'taxonomy' already exists in the array. If it does, I want to add the id from the new object only to that existing object. Although I know how to check if the property already exists, I am unsure about how to properly add the new id to the array.

Upon adding the above-mentioned object, the resulting array should look like this:

    [
        { taxonomy: 'category', id: [ 10, 100, 30 ] }, // Added 30
        { taxonomy: 'post_tag', id: [ 20 ] },
    ];

If the object does not yet exist, it should be added accordingly. Could someone provide assistance with this issue?

Answer №1

Using the method Array.find(), you can search for an object in the array with the same taxonomy. If one is found, then add the id to it. If none is found, create a copy of the object and push it into the array after converting the object's id to an array:

const updateArray = obj => {
  const current = arr.find(o => obj.taxonomy === o.taxonomy);
  
  if(current) current.id.push(obj.id);
  else arr.push({
    ...obj,
    id: [obj.id]
  })
};

const arr = [
  { taxonomy: 'category', id: [ 10, 100 ] },
  { taxonomy: 'post_tag', id: [ 20 ] },
];

updateArray({ taxonomy: 'category', id: 30 });

updateArray({ taxonomy: 'other', id: 50 });

console.log(arr);

Answer №2

To update or add a new object with the specified id to an array, you can follow this approach.

const
    array = [{ taxonomy: 'category', id: [ 10, 100 ] }, { taxonomy: 'post_tag', id: [ 20 ] }];
    object = { taxonomy: 'category', id: 30 },
    item = array.find(({ taxonomy }) => object.taxonomy === taxonomy);

if (item) {
    item.id.push(object.id);
} else {
    array.push(Object.assign({}, object, { id: [object.id] }));
}

console.log(array);

   // remove the last insert
   // find item with taxonomy and id
   item =  array.find(({ taxonomy, id }) => object.taxonomy === taxonomy && id.includes(object.id));

// remove from id by using the index
if (item) item.id.splice(item.id.indexOf(object.id), 1);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To iterate through and add a new ID, you can utilize the forEach function.

let items = [{type: 'fruit', ids: [5, 10]},{type: 'vegetable', ids: [15]},],
    newItem = {type: 'fruit', ids: 20};

items.forEach(({type, ids}) => {
  if (newItem.type === type) {
    ids.push(newItem.ids);
  }   
});

console.log(items);

Answer №4

By implementing the upsert() function as shown in the code snippet below, you can achieve this task with a level of abstraction that allows for versatility beyond just one specific schema. The upsert() function comes with default settings that are suitable when dealing with objects that consist of primitive values.

function upsert (
  array, object, keyFn,
  updateFn = (target, object) => Object.assign(target, object),
  insertFn = object => object
) {
  const key = keyFn(object)
  const index = array.findIndex(
    value => keyFn(value) === key
  )

  if (index !== -1) updateFn(array[index], object)
  else array.push(insertFn(object))
}

let arr = [
  { type: 'fruit', id: [5, 50] },
  { type: 'vegetable', id: [15] }
]

const obj = { type: 'fruit', id: 25 }

upsert(
  arr, obj,
  o => o.type, // determines whether to update existing object
  (t, o) => t.id.push(o.id), // updates existing object
  ({ id, ...o }) => ({ ...o, id: [id] }) // defines new object to insert
)

console.log(arr)

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

Utilizing arrays in Expressjs: Best practices for passing and utilizing client-side arrays

Here is the structure of an object I am dealing with: editinvite: { _id: '', title: '', codes_list: [] } The issue I am facing is that I am unable to access the codes_list property in my NodeJS application. It appears as 'u ...

Issues with syntax in AJAX programming can be a significant road

I have a function linked to an onclick button event. This function sends data via ajax to another php file. Everything was working smoothly until I tried to add an IF statement to the 'success' section, which would receive true or false from an e ...

Malfunction detected in JavaScript shopping cart functionality

Trying to implement a functional shopping cart on a webpage has been a challenge for me. I've encountered issues in my JavaScript code that are preventing the cart from working as intended. As a newbie to JavaScript, I'm struggling to pinpoint th ...

Sort users by their data attribute using jQuery

I need to sort users based on their data attribute. Within the main div called user-append, I have a variable number of users retrieved from an ajax get request. It could be 3 users or even up to 100, it's dynamic. Here is the structure with one user ...

Unexpectedly, the React custom component is failing to render as intended

I am anticipating the text "SMALL Medium, Big" to be displayed on the screen but unfortunately it's not showing up function Box(prop){ const ele = <div className={prop.cn}> </div> return ele } ...

Utilizing multiple instances of Express in Node.js

I've been struggling to grasp how the Expressjs framework for Node.js manages routes across multiple files. In my main index.js file, the setup looks something like this: var express = require('express'); var app = express(); app.use(' ...

An issue occurred while attempting to pretty-print JSON in Typescript

Currently, I am attempting to utilize https://www.npmjs.com/package/prettyjson in conjunction with Typescript; however, it is unable to locate the module. To begin, I created a package.json file: { "name": "prettyjson-test", "description": "prettyjso ...

When the click event is triggered on the modal, the page suddenly jumps to the top while applying the style of hiding the element

After implementing a modal that appears upon clicking an element on my webpage, I encountered an issue when trying to close it. I added an event listener to the 'close' link element in the top right corner of the modal with the following code sni ...

Is it feasible in ES6 Javascript to access properties or methods of the superclass in a child class without the necessity of utilizing the "this" keyword?

Exploring Javascript ES6: Accessing Parent Class Properties in Child Class class Animal { constructor() { this.sound = 'roar' this.species = 'lion' } } class Lion extends Animal { constructor() { ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

A guide to the bottom border of text inputs in React Native

Trying to create a borderless text input has been a challenge for me. After applying the necessary properties, a bottom border line in black color appeared. View image of text input I am looking for a way to remove this border completely. import { TextIn ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

The higher-order component is lacking a defined display name in its definition

Struggling to develop a higher order component, I keep receiving an eslint warning. The component definition is missing a display name. Even after attempting to include a display name as shown below, the warning persists. import React from 'react ...

I am looking to store individual objects in LocalStorage, however, I currently have the entire array saved

Struggling to figure out how to save a single object instead of the whole array when creating a movie watchlist. Clicking "add to watchlist" should save the single object in LocalStorage, while clicking "remove from watchlist" should remove it. I've a ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

Combining data types in TypeScript (incorporating new keys into an existing keyof type)

If I have a typescript type with keys: const anObject = {value1: '1', value2: '2', value3: '3'} type objectKeys = keyof typeof anObject and I want to add additional keys to the type without manually defining them, how can I ...

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...

Iterating through HTML table data using a JQuery for each loop

Currently, I have an HTML table that is structured in the following way: <div class="timecard"> <h3>tommytest</h3> <table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;"> < ...