简体   繁体   中英

Modify specific values within a JSON Object, return a cloned version of the object with modified values?

I am trying to modify an obj similar to this:

{
  "data": [
    {
      "id": "0923f8e0-d090-11ea-8615-9d076fb270e8",
      "pb_id": "or-portland-188",
      "state": "Oregon",
      "city": "Portland",
      "date": "2020-07-27T00:00:00.000000Z",
      "title": "Journalist shot in the face",
      "description": null,
      "data": null,
      "geocoding": { "lat": 45.5051064, "long": -122.6750261 }
    },
    {
    ...
    },
   ]
}

I need to go into every instance of the "geocoding" key, and modify the lat/long values slightly as all of the coordinates I have are identical.

I have a function to add a small amount of randomness, but I'm having trouble accessing the values and getting the entire object with modified values returned.

If you needed to go in and change all of the lat/long values (let's say multiply them all by 0 for demonstration sake), how would you do this?

EDIT: This is my solution, thank you @cyberwombat

const newData = pbdb.data.map(item => {
  const x = item.geocoding.lat;
  const y = item.geocoding.long;
  return {
    ...item,
    geocoding: {
      lat: parseFloat(x) + 2 * 0.05 * (Math.random() - 0.5),
      long: parseFloat(y) + 2 * 0.05 * (Math.random() - 0.5),
    },
  };
});

You can map through it like this:

const newData = data.map(item => {
  return { ...item, geocoding: { lat: 45.5051064 * 2, long: -122.6750261 * 2 } }
}

or with values unrelated to item - here I call external functions to randomize or do whatever:

// Some geo
const someLat = origLat => { 
  return 111 // could generate something random 
}
const someLong = origLong => { 
  return origLong * 2 // could generate something random 
}

const newData = data.map(item => {
  const { geocoding: { lat, long }} = item // Double spread...
  return { ...item, geocoding: { lat: someLat(lat), long: someLong(long) } }
}

Here's info on map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

And the spread operator to merge objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

You could try something like this

 const { data } = { data: [ { id: "0923f8e0-d090-11ea-8615-9d076fb270e8", pb_id: "or-portland-188", state: "Oregon", city: "Portland", date: "2020-07-27T00:00:00.000000Z", title: "Journalist shot in the face", description: null, data: null, geocoding: { lat: 45.5051064, long: -122.6750261 }, }, ], } const res = data.map((element) => { element.geocoding.lat += 1 element.geocoding.long += 1 // any other modification if have return element }) console.log(res)

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