If an array contains a property, add it to the object

I have a set of objects with unique identifiers, and there's also an array containing specific identifier values. I want to mark the objects that have an id matching any value in the array by adding a new property called found and setting it to true. My initial thought is to utilize the findIndex function for this operation.

const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']

Desired Result

const arrayOfObjects = [ { id: '123' }, { id: '456', found: true }, { id: '789' } ]

Answer №1

const objectArray = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const idArray = ['456']

objectArray.map((obj) => {
  if(idArray.includes(obj.id)) {
    obj.found = true;
  }
})

console.log(objectArray);

Answer №2

If you convert your arrayOfIds to a Set, it can significantly improve lookup speed at O(1).

const idsSet = new Set(arrayOfIds);
const updatedObjects = arrayOfObjects.map(item => {
  if (idsSet.has(item.id)) {
    item.updatedField = true;
  }
  return item;
});

Answer №3

To utilize the power of JavaScript, you can convert an array into a Set and then take advantage of Array#map in conjunction with Set#has.

const arrayOfPeople = [ { name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' } ]
const namesToFind = new Set(['Bob']);
const result = arrayOfPeople.map(person => ({...person, ...namesToFind.has(person.name) && {found: true}}));
console.log(result);

Answer №4

To iterate through the objects and extend the object using the found property, you can employ the mapping technique.

const updatedOutput = arrayOfObjects.map((item) => {
   if (arrayOfIds.includes(item.id)) {
      return {  ...item, found: true };
   }
   return item;
});

Answer №5

To simplify the process, you can create a lookup object based on the 'arrayOfIds'. By mapping through 'arrayOfIds' and creating key-value pairs with the ids as keys and an object with 'found' set to true as values, you can then use this lookup object when iterating over the 'arrayOfObjects' array to make necessary modifications.

const arrayOfObjects = [{ id: '123' }, { id: '456' }, { id: '789' }];
const arrayOfIds = ['456'];
const lookup = Object.fromEntries(arrayOfIds.map((x) => [x, { found: true }]));
const ret = arrayOfObjects.map((x) => ({ ...x, ...lookup[x.id] }));
console.log(ret);

Answer №6

To iterate through the array of objects and update them accordingly, you can use a combination of the map method and the includes function to determine if an object needs modification. If the condition is met, add show: true by spreading the existing object; otherwise, return the original object as it is. This code snippet demonstrates this concept:

const arrayOfObjects = [{ id: "123" }, { id: "456" }, { id: "789" }];
const arrayOfIds = ["456"];
const result = arrayOfObjects.map((item) => {
  if (arrayOfIds.includes(item.id)) {
      return {
              ...item,
              show: true
      };
  }
  return item;
});
console.log(result);

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

Error encountered: The call stack size has been exceeded due to the combination of Node JS, MongoDB, and Mongoose

I am facing a RangeError issue while attempting to create a new object using a predefined schema and inserting it into my mongodb database. I need assistance in debugging this error and finding a solution for it. Any help would be appreciated, thanks. App ...

Tips for displaying a hyperlink in an Angular 6 component template

In my Angular 6 application, I am facing an issue with a component that is used to display messages on the page. Some of the messages include hyperlinks in HTML markup, but they are not being rendered properly when displayed (they appear as plain text with ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

What is the reason behind these two objects being considered equal (==)?

I am facing an issue with PHP where I have two objects that seem to be different due to the $_frets variable, yet PHP is showing that ($o1 == $o2) == TRUE. Can someone explain this? Here is the dump of $o1: guitarChord Object ( [_guitarChord:guitarCh ...

I'm having trouble with using setInterval() or the increment operator (i+=) while drawing on a canvas in Javascript. Can anyone help me out? I'm new

I am looking to create an animation where a square's stroke is drawn starting from the clicked position on a canvas. Currently, I am facing an issue where the values of variables p & q are not updating as expected when drawing the square at the click ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

Allow entry fields and a submit button to become active once the form has been submitted on ASP.NET MVC 4

I want the update button to be activated after submitting the form. Take a look at my code: VIEW: @using (Html.BeginForm("ProcessTech", "Home", FormMethod.Post)) { @Html.TextBoxFor(m => m.techNo, new { @class = "form-control maintain-t ...

Adjust the text color of a div element by clicking a button with the help of JavaScript

I am trying to change the font color of my div when a button is clicked using JavaScript. The two buttons I have are 'Green' and 'Red'. <button type="button" class="green">Green</button> <button type="button" class="red" ...

Sharing resources between different origins and the file:// protocol

I have been developing an HTML5 application that is collecting data from various sources using JSONP. So far, everything involving a GET request has been functioning perfectly. However, I have encountered a hurdle while attempting to make a POST request. T ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

Refreshing the three.js scene seamlessly within a single-page web application

I am currently working on a single page application that consists of multiple "slides," each implemented as a different hidden div, which becomes visible when it is the current slide. One of these slides features a canvas element and a ThreeJS scene. The ...

The efficiency of Ajax JSON timeouts needs improvement

Currently, I'm in the process of developing an interactive map with specific functionalities. Essentially, the user will click on a year (stored as var currentyear) and then select a country (its name stored as var thenameonly). Subsequently, an AJAX ...

Learn how to efficiently send multiple image files to the server by utilizing Formidable and React JS

I am encountering an issue while attempting to upload five images to the server. The code file is provided below, and any assistance would be greatly appreciated. In this scenario, I am inputting image files and storing them in an array, but Formidable in ...

The dynamic text feature in my Angular Material gridlist functions perfectly in CodePen, however, it fails to work when

I have enhanced the Angular material gridlist demo by incorporating static and dynamic texts into the grid tiles. While this modification works flawlessly on Codepen (see my provided link), it does not function properly when deployed on my server. The sta ...

Tips for setting a Bootstrap 3 dropdown menu to automatically open when located within a collapsed navbar

Is there a way to have my dropdown menu automatically open when the collapsed navbar is opened? Take a look at this example I created in a fiddle to see what I'm working with so far. Right now, when you click on the navbar in its collapsed state, two ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

"Implementing a jQuery dialog box that sends JSON response to a different page rather than the current

Currently, I am working on an MVC application where I need to insert properties of certain objects. To achieve this, I have created a modal popup using jQuery dialog. In order to avoid any interference with other user actions, I have implemented an Ajax.Be ...