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

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

Exploring the depths of a JArray with thorough investigation

Below is a JSON structure that I am working with: [ ["Identity"], // 0 ["Contact Information"], // 1 ["Service Fields"], // 2 ["Addresses", "Bank Accounts"] // 3 ] I want to create a C# method that utilizes Json.NET to find the index of a ...

Is it possible to manipulate a modal within a controller by utilizing a certain attribute in HTML, based on specific conditions (without relying on any bootstrap services), using AngularJS?

Within my application, I have a modal that is triggered by clicking on a button (ng-click) based on certain conditions. Here is the HTML code: <button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert ...

Click and Rotate for More Information

Hello everyone, I have a question regarding creating a unique Tumblr theme. My goal is to make the posts rotate on the y-axis when clicked, revealing like and reblog information. Currently, I've been able to achieve this effect on hover by using code ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

Why isn't my textarea in jQUERY updating as I type?

On my website, I have a comment script that is not functioning correctly in some parts of the jQuery/JavaScript code. Instead of posting an edited comment to PHP, I created a notification window to test if the value passed through is actually changing. W ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...

Adapting the visible outcome based on the second figure of a numerical value

Is there a way to automatically change the displayed value using a Vue filter when the last digit of the value falls within a specific range, such as 2-4? I am looking for a solution that can work for all possible intervals like (22-24, 32-34, 622-624... ...

Searching and editing JSON objects using C#

Is it possible to search for and change specific values within a Json string without the need for serialization and deserialization? ...

Retrieve the most recent ajax request and cancel any other ones

I've been exploring this issue and it seems fairly straightforward, but I'm having trouble finding a solution. I have several requests that call different URLs. However, for each URL, I only want to receive the last result from the same URL being ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

Tips for ensuring all images are the same size within a div element

https://i.stack.imgur.com/EkmWq.jpg Is there a way to make sure all the images fit perfectly inside their respective border boxes without appearing stretched? I've tried setting fixed height and width within a div, but they always end up looking off. ...

The event listener attached to this model is failing to trigger when there are

The issue is that the "change" event is not being triggered in the code snippet below. var PageView = Backbone.View.extend({ el: $("body"), initialize: function(){ this.model.on("change:loading", this.loader, this); }, loader: func ...

Tips for maintaining reactivity in nested object properties in external JavaScript class files without relying on Vue.set()

In my possession is this particular component: <template> <div class="simple-editor"> {{editor.view.toolbarManager.buttons}} <component v-for="(button, name) in editor.view.toolbarManager.buttons" ...

Vue component does not display FabricJS image

Currently, I am facing an issue where I want to manipulate images on a canvas using FabricJS inside a VueJS app. In the view component, there is a prop called background which I pass in and then use fabric.Image.fromURL() to load it onto the canvas. Howeve ...

Is there a method in Express to verify which URL a post is being sent to?

At the moment, I am using express to proxy my session creation URL in the following manner: app.post('/sessions', (req, res) => { // Code goes here }) The code that is used for this proxy also needs to be applied to my /confirmation endpoi ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Firefox does not support the event

// This function makes rows draggable within a table by utilizing mouse events. // It handles the drag initiation, movement, and stopping of the drag operation. makeRowsDraggable: function() { var dragInitiated = false; var startPageX, startPageY ...