What is the best way to change the value of a key in a JSON Object?

I am currently utilizing _underscore library. My goal is to change the value of a specific key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];
 
var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

In the output displayed in console.log(index), I aim to modify the value of the key (name) by appending "-Copy".

Desired result

{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}

I only intend to add -Copy to the existing value of the key (name).

Answer №1

Simply make changes to the located object.

var users = [{ _id: { $oid: "3426" }, name: "peeter" }, { _id: { $oid: "5a027" }, name:"ken" }, { _id: { $oid: "5999" }, name: "karmal" }],
    item = _.find(users, function(o) { return o._id.$oid == '5999'; });

if (item) {               // verify if item is found
    item.name += '-Copy'; // modify property value
}
console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Answer №2

Using the strength of Higher-order functions

var users = [
    {"_id":{"$oid":"3426"},
    "name":"peeter"
    },
    {"_id":{"$oid":"5a027"},
    "name":"ken"
    },
    {"_id":{"$oid":"5999"},
    "name":"karmal"
    }
  ];

var findSpecific$oid=function(oid){ 
    return function(obj) { return obj["_id"]["$oid"]===oid; };
  }

var appendExtensionInName=function(extension){ 
    return function(obj){ 
        var newObj = {};
        newObj["_id"]=obj["_id"]
        newObj["name"]=obj["name"] +"-"+extension;
        return newObj;
      };
  }

var selectedUser=users.filter(findSpecific$oid("5999")).map(appendExtensionInName("copy"))

Answer №3

Give this a shot:

for(let j = 0; j < clients.length; j++) {
    if(clients[j]._id.$oid == 5999) {
        clients[j].name += "-Duplicate"; 
    }
}

Answer №4

Here is the code snippet:

var users = [
  {"_id":{"$oid":"3426"},
  "name":"peeter"
  },
  {"_id":{"$oid":"5a027"},
  "name":"ken"
  },
  {"_id":{"$oid":"5999"},
  "name":"karmal"
  }
];
 
var result = _.find(users, function(obj) { 
    if(obj._id.$oid == '5999'){
      obj.name += '-Duplicate';
      return obj._id.$oid == '5999'; 
    }
  });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

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

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

An issue has arisen with AngularJS and Twitter Bootstrap, displaying an error message stating that the function element.focus

I recently implemented the angularjs twitter bootstrap datepicker and everything seemed to be working smoothly. However, I encountered an error when trying to click on the text box for the popup datepicker. This issue has left me puzzled as I am still new ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

Using ObjectIDs in MongoDB may be successful, however, it may not function properly in Mongoose

The desired effect is successfully achieved by the first code snippet shown below: //in mongodb console: db.collection.update({"username":"name"}, {$pull : { "task" : { "_id" : ObjectId("55280205702c316b6d79c89c")}}}) However, the second code snippet wri ...

Is it possible to load modal content using ajax bootstrap pagination without having to refresh the main page?

Whenever I utilize the bootstrap modal and pagination for modal content, clicking the next/prev button causes the entire page, including the main window, to reload. Here are the scripting lines: $("#ajax_process_page").html("<%= escape_javascript(rend ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Issue encountered: Unforeseen command: POST karma

Whenever I try to run my test cases, I encounter the following error message: Error: Unexpected request: POST data/json/api.json it("should $watch value", function(){ var request = '/data/json/api.json'; $httpBackend.expectPOST(reque ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

How can you access PHP $_GET values using JavaScript?

Recently, I encountered an issue with my app that is running on localhost/index.php. In my JavaScript code, I am using the History API as follows: history.replaceState({}, null, "?uid=" + uid); to update the URL of the page. Here, the variable uid holds ...

Trouble with displaying a custom marker on Google Maps API v3

I have been struggling to replace the default marker with a custom icon in my Google Maps code. Despite my efforts and thorough research, I cannot seem to get it to work correctly. Below is the snippet of my code: <script type="text/javascript"> fu ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

A timer created using jQuery and JavaScript

Looking for a way to automatically transition between three div elements with a fade in/out effect every 8 seconds? Check out this simple code snippet I wrote: $(".link1").click(function () { $(".feature1").fadeIn(1000); $(".feature2").fadeOut(1000) ...

I am having trouble getting JQuery tablesorter to work, what am I missing?

As a newcomer to jQuery, I am attempting to implement Tablesorter, but unfortunately, it does not seem to be functioning properly on my table (the styling remains unaffected by the tablesorter css, and the sorting functionality is non-existent). Below is ...

Transforming JSON data into CSV format using Python

I am seeking assistance with extracting statistical data tables from NHL.com and converting them into CSV format for use in Excel later. While I have successfully extracted the tables, I am encountering difficulties when attempting to convert them to CSV. ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

There was an error with CreateListFromArrayLike as it was called on a non-object

I am receiving a list of over 1000 numbers from an API and storing it in a variable called "number". My goal is to find the highest number from this list. However, I encountered an error while attempting to do so: TypeError: CreateListFromArrayLike called ...

Is there a way to use Spring MVC annotation-based controller for portlets to render a JSON view/response via AJAX?

After spending a significant amount of time searching Google and stackoverflow, I have not been able to find a solution to my problem. As a PHP developer originally, returning a JSON array from a PHP controller is easy for me. However, now that I am worki ...