Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this:

[
  {
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Bob'
  },
  {
    id: 3,
    name: 'Eve'
  }
]

My goal is to locate an object by its id and append a deleted: true property to it.

I'm curious about the most straightforward method to achieve this.

Answer №1

If you're looking to update an object within an array, you can utilize the following versatile function by providing the array and the id of the object as parameters.

var arr = [
  {
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Bob'
  },
  {
    id: 3,
    name: 'Charlie'
  }
];

function modifyObject(data, id){
  data.forEach(obj => {
    if(obj.id === id){
      obj['updated'] = true;
    }
  });
   return data;
}

let id = 2;
console.log(modifyObject(arr, id));

Answer №2

If you need to find a specific user in an array, using Array.prototype.find is the most straightforward approach.

let employees = [
  {
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Bob'
  },
  {
    id: 3,
    name: 'Carol'
  }
];
let id = 2;
let foundEmployee = employees.find(employee => employee.id === id);

console.log('Employees before update', employees);
foundEmployee.status = 'Inactive';
console.log('Employees after update', employees);

Answer №3

Give this a try:

var array = [
    {
        id: 1,
        name: 'John'
    },
    {
        id: 2,
        name: 'Jack'
    },
    {
        id: 3,
        name: 'Peter'
    }
]

for (var item in array){
    if (array[item].id === 1){
        array[item].deleted = true;
        break;
    }
}
console.log(array)

This code snippet iterates through each element in the array and checks if the specified value is present. If it finds a match, it adds a boolean attribute named deleted to that element and then exits the loop.

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

Get the div to occupy the rest of the available height

I am facing a challenge with two divs on my webpage. The bottom one contains content that expands the highest. The page is set to 100% height and width using the CSS property position: absolute. <style> body, html { height:100%, width:100% } ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Using Jmeter's JSON Extractor for parsing response and extracting token value

Currently facing an issue with extracting the "webToken" response. I have attempted using both $..webToken and $.webToken as JSON path expressions, but no luck so far. Any suggestions on how to correctly extract this information? This is for use in JMete ...

Using Node.js and Express with MySQL to store documents (outcomes)

I recently developed an Express App using Node.js Express v4.16.2 MySQL v2.15.0 In my app, I have configured MySQL as a Document Store Columns id: integer value: JSON When querying the MySQL Database with mysql, I receive the following result: Ro ...

The integration between React hook form and reactstrap input components is not functioning properly

Having an issue with react-hook-form and reactstrap. The component List.jsx is causing trouble: import { useContext, useEffect } from "react"; import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider'; import { Link } from "react- ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

"Exploring the power of Node.js by utilizing ObjectArray and implementing

Can I compare two arrays of objects in JavaScript? My goal is to find the common objects between these two arrays: First object array: [ { id_0: 356, name_0: 'xxxxx', id_1: 33, name_1: 'yyyyyy', id_ ...

How can I utilize a callback in TypeScript when working with interfaces?

Can someone guide me on how to implement an interface in typescript with callback function? interface LoginCallback{ Error: boolean, UserInfo: { Id: string, OrganizationId: string } } interface IntegrationInterface { Ini ...

Error with redirect in Ajax request

I have a question regarding an Ajax issue (not using jQuery)... I am trying to extract the URL from a blog that has an RSS feed in XML format. I am attempting to access the link using Ajax, which is working fine most of the time. However, sometimes I enco ...

What is the best way to use jest/enzyme to determine if a method from an imported class was called in a component

Here is the code snippet from my component: export class VehiclesComponent extends React.Component { constructor(props) { super(props); this.state = { data: [], }; autoBind(this); } componentDidMount () { this.fetchData(); ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...

The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0). For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est". The current code snippet ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

How to effortlessly convert a JSON string into a JavaScript object

Hello everyone, I am working with DynamoDB and need to parse the JSON Object that is returned from a call in order to retrieve the password hash field. jsonString = JSON.stringify(data) console.log(jsonString) This is what the output looks like: {"Count ...

Error encountered during JSON object conversion

How can I convert the string below into an object? "{"taskStatus":"Not Started","taskFields":{"originalTransactionDate":"${datafield:feerefund:originalTranDate}","transactionPostingDate":"${datafield:feerefund:tranPostingDate}","referenceNumber":"${data ...

Changing the contents of NamedTemporaryFile in Python 3

I'm encountering a challenge when trying to modify the content of a NamedTemporaryFile after its initial creation. In my specific case, I am creating a NamedTemporaryFile from JSON data retrieved from a URL. My objective is to later open and edit th ...

Is the express.json() middleware for parsing JSON request body designed to handle synchronous calls?

According to Express.js's documentation, it is recommended to avoid using synchronous functions as much as possible. This is because in high-traffic websites, the accumulation of synchronous calls can negatively impact the performance of the applicati ...

What does the error message "unsupported command-line flag" in Chrome mean for Protractor?

Recently jumping on the Protractor bandwagon, I found myself facing an issue while running my tests on Chrome (an error message appears below the address bar in the browser): A worrisome warning popped up saying something about '--ignore-certificat ...