[javascript] How to change value of object which is inside an array using JavaScript or jQuery?

The code below comes from jQuery UI Autocomplete:

var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];

For example, I want to change the desc value of jquery-ui. How can I do that?

Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....

This question is related to javascript jquery arrays

The answer is


You can use map function --

const answers = this.state.answers.map(answer => {
  if(answer.id === id) return { id: id, value: e.target.value }
  return answer
})

this.setState({ answers: answers })

try using forEach(item,index) helper

var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];

let search_to_change = 'jquery'

projects.forEach((item,index)=>{
   if(item.value == search_to_change )
      projects[index].desc = 'your description ' 
})


We can also use Array's map function to modify object of an array using Javascript.

function changeDesc(value, desc){
   projects.map((project) => project.value == value ? project.desc = desc : null)
}

changeDesc('jquery', 'new description')

The best solution, thanks to ES6.

This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".

const newProjects = projects.map(p =>
  p.value === 'jquery-ui'
    ? { ...p, desc: 'new description' }
    : p
);

ES6 way, without mutating original data.

var projects = [
{
    value: "jquery",
    label: "jQuery",
    desc: "the write less, do more, JavaScript library",
    icon: "jquery_32x32.png"
},
{
    value: "jquery-ui",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"
}];

//find the index of object from array that you want to update
const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui');

// make new object of updated object.   
const updatedObj = { ...projects[objIndex], desc: 'updated desc value'};

// make final new array of objects by combining updated object.
const updatedProjects = [
  ...projects.slice(0, objIndex),
  updatedObj,
  ...projects.slice(objIndex + 1),
];

console.log("original data=", projects);
console.log("updated data=", updatedProjects);

Try this code. it uses jQuery grep function

array = $.grep(array, function (a) {
    if (a.Id == id) {
        a.Value= newValue;
    }
    return a;
});

you need to know the index of the object you are changing. then its pretty simple

projects[1].desc= "new string";

Let you want to update value of array[2] = "data"

    for(i=0;i<array.length;i++){
      if(i == 2){
         array[i] = "data";
        }
    }

let thismoth = moment(new Date()).format('MMMM');
months.sort(function (x, y) { return x == thismoth ? -1 : y == thismoth ? 1 : 0; });

It's easily can be accomplished with underscore/lodash library:

  _.chain(projects)
   .find({value:"jquery-ui"})
   .merge({desc: "new desc"});

Docs:
https://lodash.com/docs#find
https://lodash.com/docs#merge


This is another answer involving find. This relies on the fact that find:

  • iterates through every object in the array UNTIL a match is found
  • each object is provided to you and is MODIFIABLE

Here's the critical Javascript snippet:

projects.find( function (p) {
    if (p.value !== 'jquery-ui') return false;
    p.desc = 'your value';
    return true;
} );

Here's an alternate version of the same Javascript:

projects.find( function (p) {
    if (p.value === 'jquery-ui') {
        p.desc = 'your value';
        return true;
    }
    return false;
} );

Here's an even shorter (and somewhat more evil version):

projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );

Here's a full working version:

_x000D_
_x000D_
  var projects = [_x000D_
            {_x000D_
                value: "jquery",_x000D_
                label: "jQuery",_x000D_
                desc: "the write less, do more, JavaScript library",_x000D_
                icon: "jquery_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "jquery-ui",_x000D_
                label: "jQuery UI",_x000D_
                desc: "the official user interface library for jQuery",_x000D_
                icon: "jqueryui_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "sizzlejs",_x000D_
                label: "Sizzle JS",_x000D_
                desc: "a pure-JavaScript CSS selector engine",_x000D_
                icon: "sizzlejs_32x32.png"_x000D_
            }_x000D_
        ];_x000D_
_x000D_
projects.find( p => p.value === 'jquery-ui' && ( p.desc = 'your value', true ) );_x000D_
_x000D_
console.log( JSON.stringify( projects, undefined, 2 ) );
_x000D_
_x000D_
_x000D_


It is quite simple

  • Find the index of the object using findIndex method.
  • Store the index in variable.
  • Do a simple update like this: yourArray[indexThatyouFind]

_x000D_
_x000D_
//Initailize array of objects._x000D_
let myArray = [_x000D_
  {id: 0, name: "Jhon"},_x000D_
  {id: 1, name: "Sara"},_x000D_
  {id: 2, name: "Domnic"},_x000D_
  {id: 3, name: "Bravo"}_x000D_
],_x000D_
    _x000D_
//Find index of specific object using findIndex method.    _x000D_
objIndex = myArray.findIndex((obj => obj.id == 1));_x000D_
_x000D_
//Log object to Console._x000D_
console.log("Before update: ", myArray[objIndex])_x000D_
_x000D_
//Update object's name property._x000D_
myArray[objIndex].name = "Laila"_x000D_
_x000D_
//Log object to console again._x000D_
console.log("After update: ", myArray[objIndex])
_x000D_
_x000D_
_x000D_


Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.

    var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21},
        { ID: 3, FName: "John", LName: "Test3", age: 22},
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22}
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });

Output should be as follows

Ajay Smith

Jack Black

John Test3

Steve Test4


Using map is the best solution without using extra libraries.(using ES6)

const state = [
{
    userId: 1,
    id: 100,
    title: "delectus aut autem",
    completed: false
},
{
    userId: 1,
    id: 101,
    title: "quis ut nam facilis et officia qui",
    completed: false
},
{
    userId: 1,
    id: 102,
    title: "fugiat veniam minus",
    completed: false
},
{
    userId: 1,
    id: 103,
    title: "et porro tempora",
    completed: true
}]

const newState = state.map(obj =>
    obj.id === "101" ? { ...obj, completed: true } : obj
);

you can use .find so in your example

   var projects = [
            {
                value: "jquery",
                label: "jQuery",
                desc: "the write less, do more, JavaScript library",
                icon: "jquery_32x32.png"
            },
            {
                value: "jquery-ui",
                label: "jQuery UI",
                desc: "the official user interface library for jQuery",
                icon: "jqueryui_32x32.png"
            },
            {
                value: "sizzlejs",
                label: "Sizzle JS",
                desc: "a pure-JavaScript CSS selector engine",
                icon: "sizzlejs_32x32.png"
            }
        ];

let project = projects.find((p) => {
    return p.value === 'jquery-ui';
});

project.desc = 'your value'

You can use $.each() to iterate over the array and locate the object you're interested in:

$.each(projects, function() {
    if (this.value == "jquery-ui") {
        this.desc = "Your new description";
    }
});

upsert(array, item) { 
        const i = array.findIndex(_item => _item.id === item.id);
        if (i > -1) {
            let result = array.filter(obj => obj.id !== item.id);
            return [...result, item]
        }
        else {
            return [...array, item]
        };
    }

The power of javascript destructuring

_x000D_
_x000D_
const projects = [
  {
    value: 'jquery',
    label: 'jQuery',
    desc: 'the write less, do more, JavaScript library',
    icon: 'jquery_32x32.png',
    anotherObj: {
      value: 'jquery',
      label: 'jQuery',
      desc: 'the write less, do more, JavaScript library',
      icon: 'jquery_32x32.png',
    },
  },
  {
    value: 'jquery-ui',
    label: 'jQuery UI',
    desc: 'the official user interface library for jQuery',
    icon: 'jqueryui_32x32.png',
  },
  {
    value: 'sizzlejs',
    label: 'Sizzle JS',
    desc: 'a pure-JavaScript CSS selector engine',
    icon: 'sizzlejs_32x32.png',
  },
];

function createNewDate(date) {
  const newDate = [];
  date.map((obj, index) => {
    if (index === 0) {
      newDate.push({
        ...obj,
        value: 'Jquery??',
        label: 'Jquery is not that good',
        anotherObj: {
          ...obj.anotherObj,
          value: 'Javascript',
          label: 'Javascript',
          desc: 'Write more!!! do more!! with JavaScript',
          icon: 'javascript_4kx4k.4kimage',
        },
      });
    } else {
      newDate.push({
        ...obj,
      });
    }
  });

  return newDate;
}

console.log(createNewDate(projects));
_x000D_
_x000D_
_x000D_


Find the index first:

function getIndex(array, key, value) {
        var found = false;
        var i = 0;
        while (i<array.length && !found) {
          if (array[i][key]==value) {
            found = true;
            return i;
          }
          i++;
        }
      }

Then:

console.log(getIndex($scope.rides, "_id", id));

Then do what you want with this index, like:

$scope[returnedindex].someKey = "someValue";

Note: please do not use for, since for will check all the array documents, use while with a stopper, so it will stop once it is found, thus faster code.


_x000D_
_x000D_
// using higher-order functions to avoiding mutation_x000D_
var projects = [_x000D_
            {_x000D_
                value: "jquery",_x000D_
                label: "jQuery",_x000D_
                desc: "the write less, do more, JavaScript library",_x000D_
                icon: "jquery_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "jquery-ui",_x000D_
                label: "jQuery UI",_x000D_
                desc: "the official user interface library for jQuery",_x000D_
                icon: "jqueryui_32x32.png"_x000D_
            },_x000D_
            {_x000D_
                value: "sizzlejs",_x000D_
                label: "Sizzle JS",_x000D_
                desc: "a pure-JavaScript CSS selector engine",_x000D_
                icon: "sizzlejs_32x32.png"_x000D_
            }_x000D_
        ];_x000D_
_x000D_
// using higher-order functions to avoiding mutation_x000D_
index = projects.findIndex(x => x.value === 'jquery-ui');_x000D_
[... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)];
_x000D_
_x000D_
_x000D_


You can create your specific function like the below, then use that everywhere you need.

var each    = (arr, func) => 
                Array.from(
                    (function* (){
                        var i = 0;
                        for(var item of arr)
                            yield func(item, i++);
                    })()
                );

Enjoy..


This is my response to the problem. My underscore version was 1.7 hence I could not use .findIndex.

So I manually got the index of item and replaced it. Here is the code for the same.

 var students = [ 
{id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" },
{id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" },
{id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" },
{id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" }
               ]

Below method will replace the student with id:4 with more attributes in the object

function updateStudent(id) {
 var indexOfRequiredStudent = -1;
    _.each(students,function(student,index) {                    
      if(student.id === id) {                        
           indexOfRequiredStudent = index; return;      
      }});
 students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"});           

}

With underscore 1.8 it will be simplified as we have methods _.findIndexOf.


to update multiple items with the matches use:

_.chain(projects).map(item => {
      item.desc = item.value === "jquery-ui" ? "new desc" : item.desc;
      return item;
    })

Here i am using angular js. In javascript you can use for loop to find.

    if($scope.bechval>0 &&$scope.bechval!=undefined)
    {

                angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
                $scope.model.benhmarkghamlest[key].bechval = $scope.bechval;

            });
    }
    else {
        alert("Please sepecify Bechmark value");
    }

Assuming you wanted to run a bit more complicated codes during the modification, you might reach for an if-else statement over the ternary operator approach

// original 'projects' array;
var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];
// modify original 'projects' array, and save modified array into 'projects' variable
projects = projects.map(project => {
// When there's an object where key 'value' has value 'jquery-ui'
    if (project.value == 'jquery-ui') {

// do stuff and set a new value for where object's key is 'value'
        project.value = 'updated value';

// do more stuff and also set a new value for where the object's key is 'label', etc.
        project.label = 'updated label';

// now return modified object
        return project;
    } else {
// just return object as is
        return project;
    }
});

// log modified 'projects' array
console.log(projects);

given the following data, we want to replace berries in the summerFruits list with watermelon.

const summerFruits = [
{id:1,name:'apple'}, 
{id:2, name:'orange'}, 
{id:3, name: 'berries'}];

const fruit = {id:3, name: 'watermelon'};

Two ways you can do this.

First approach:

//create a copy of summer fruits.
const summerFruitsCopy = [...summerFruits];

//find index of item to be replaced
const targetIndex = summerFruits.findIndex(f=>f.id===3); 

//replace the object with a new one.
summerFruitsCopy[targetIndex] = fruit;

Second approach: using map, and spread:

const summerFruitsCopy = summerFruits.map(fruitItem => 
fruitItem .id === fruit.id ? 
    {...summerFruits, ...fruit} : fruitItem );

summerFruitsCopy list will now return an array with updated object.


I think this way is better

const index = projects.findIndex(project => project.value==='jquery-ui');
projects[index].desc = "updated desc";

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?