简体   繁体   中英

how to change a element inside an array in javascript and store it in new array

i'm new to javascript I have an array of objects like

arr=[{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}]

what if i want to increase the value of likes by 1 where id is 1 and store the resulting array in arr2 ???

arr2=[{id:1,likes:11},{id:3,likes:13},{id:3,likes:1}]

You can Do like this

 const arr = [{ id: 1, likes: 10 }, { id: 3, likes: 13 }, { id: 3, likes: 1 }] const arr2 = [] let obj = {} for (let i = 0; i < arr.length; i++) { if (arr[i]['id'] === 1) obj = { id: arr[i]['id'], likes: arr[i]['likes'] + 1 } else obj = arr[i] arr2.push(obj) } console.log("arr",arr) console.log("arr2",arr2)

Using map()

 const arr = [{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}] const arr2 = arr.map(i => (i.id === 1 && (i.likes += 1), i)) console.log(arr2)

const arr = [{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}];
const arr2 = arr.map(obj =>
  obj.id === 1 ?
    { id: obj.id, likes: obj.likes + 1 } :
    obj
); 

or maybe you want the id to be dynamic?

const increment_likes = (id, old) => old.map(obj =>
  obj.id === id ?
    { id: obj.id, likes: obj.likes + 1 } :
    obj
);
const arr2 = increment_likes(1, arr);

You can do in this way.

arr=[{id:1,likes:10},{id:3,likes:13},{id:5,likes:1}]
function increase_id_likes_by_one(id){
    for(i=0;i<arr.length;i++){
    if (arr[i]['id'] == id) {
        arr[i]['likes'] += 1;
    }
  }
  console.log(arr);
}
increase_id_likes_by_one(1);
increase_id_likes_by_one(3);
increase_id_likes_by_one(5);
increase_id_likes_by_one(5);

The function increase_id_likes_by_one will take id as argument and print the new array ( after increasing the count ).

You can use Array.map() :

 var arr=[{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}]; var id = 1 var res = arr.map((obj) => { obj.id === 1? obj.likes++: obj.likes; return obj; }); console.log(res);

An inline version of map method:

 var arr=[{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}]; var id = 1 var res = arr.map(({id, likes}) => ({ id, likes : (id === 1? ++likes : likes) })); console.log(res);

You can try with JSON.stringify() and JSON.parse() with Array.prototype.map() :

 var arr=[{id:1,likes:10},{id:3,likes:13},{id:3,likes:1}]; var arr2 = JSON.parse(JSON.stringify(arr)).map(i => { if(i.id==1) i.likes += 1; return i; }); console.log(arr); //original array without modification console.log(arr2); //new array with modification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM