How to change all values of a JSON array?

Asked

Viewed 79 times

0

var cookie = [
{"domain":".nada.com","flag":true,"expiration":"1595998766"},
{"domain":".nada.com","flag":true,"expiration":"1627534734"},
{"domain":".nada.com","flag":true,"expiration":"1595998765"}
]

// Change the values of the expiration keys to 0 all // Ex.

[
{"domain":".nada.com","flag":true,"expiration":"0"},
{"domain":".nada.com","flag":true,"expiration":"0"},
{"domain":".nada.com","flag":true,"expiration":"0"}
]
  • 4

    cookie.forEach((el) => el.expiration = 0)

  • @Marceloboni could post as a response this solution :)

  • @Marceloboni if possible could post a bro example

1 answer

2

There are a few ways to do this, but what I recommend is the use of Array.prototype.forEach()¹

var cookie = [{
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998766"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1627534734"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998765"
  }
];

cookie.forEach((el) => el.expiration = 0);

console.log(cookie);

With this you change the initial array, the foreach runs through each element of the array so you don’t have to worry about the current element index, although it is possible to use it with the syntax .forEach((el, index) => console.log(index)).

If you want to go through the array and still keep the original value of the old array for something specific, you can use the Array.prototype.map()² as follows:

var cookie = [{
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998766"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1627534734"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998765"
  }
];

var newCookie = cookie.map((el) => {
  return { ...el, expiration: 0 }
});

console.log(cookie);
console.log(newCookie);

The magic is in the use of Operator spread (...)³ along those lines: {...el, expiration: 0}. This way we take all the original contents of the array and override the value of expiration with 0.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.