-1

How can I augment a JSON object with a variable's value in JavaScript? Here's my code.

addIndexedResult = (inid) => { 
let url = 'https://jsonplaceholder.typicode.com/todos/'+inid
fetch(url)
  .then(response => response.json())
  .then(json => {
      console.log(json);
      // augment json with id & sort it out later in the browser
      let jsonAug = {inid: {...json}}; //output: {"inid":{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}}
      let my_results = this.state.myResults; 
      my_results.push(jsonAug);
      this.setState(prevState => ({
        myResults: my_results
      }));          
  })
}

Notice the output of the let jsonAug = ... statement does not evaluate the variable, inid.

How can I augment the json with the value of inid?

  • 1
    `let jsonAug = {}; jsonAug[id] = json;` or even shorter: `let jsonAug = {[id]: json};` And of course: there's no such thing as a JSON object. What you call `json` is not JSON but an object. –  Nov 27 '18 at 18:05
  • it's parsed, on the 4th line of the code. The 1st comment seems right, **but** this is not the way to set state in React - you should make a copy of `this.state`. `let nextState = Object.assign(this.state, {})` then add myResults to that and setState. – Toby Nov 27 '18 at 18:17
  • Possible duplicate of [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Heretic Monkey Nov 27 '18 at 18:19
  • Thanks, Chris G. `let jsonAug = {[inid]: json};` worked like a champ. Output: {"19":{"userId":1,"id":19,"title":"molestiae ipsa aut voluptatibus pariatur dolor nihil","completed":true}} – Love and peace - Joe Codeswell Nov 27 '18 at 19:35
  • Thanks, Heretic Monkey. I think you may be right about the Possible duplicate & an answer being in there someplace. However,1. i had trouble relating the original question over there with mine & 2. Chris G's answer in his comment is so elegant relative to my question's code. – Love and peace - Joe Codeswell Nov 27 '18 at 20:01

1 Answers1

0

You should assign the id value as returned from the fetch's json directly to the id value in jsonAug like so:

let jsonAug = {id: json.id};

A full example may look like this

addIndexedResult = (id) => { 
    let url = 'https://jsonplaceholder.typicode.com/todos/'+id
    fetch(url)
    .then(response => response.json())
    .then(json => {
        console.log(json);
        // augment json with id & sort it out later in the browser
        let jsonAug = {id: json.id}; //output: {"id":{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}}
        let my_results = this.state.myResults; 
        my_results.push(jsonAug);
        this.setState(prevState => ({
          myResults: my_results
        }));          
    })
}
Jeremy
  • 160
  • 1
  • 1
  • 11