-1

I have an JSON Object such as:

{result: 
   [ 
     { 
       "id": "1",
       "name": "name 1"
      },
      { 
       "id": "2",
       "name": "name 2"
      },
      { 
       "id": "3",
       "name": "name 3"
      }
  ]
}

I am wondering how can I add element (for example: "user":"username") into each object in this this JSON such as the result will come out:

{result: 
   [ 
     { 
       "id": "1",
       "name": "name 1",
       "user": "user 1"
      },
      { 
       "id": "2",
       "name": "name 2",
       "user": "user 2"
      },
      { 
       "id": "3",
       "name": "name 3",
       "user": "user 3"
      }
  ]
}

I was trying to do something like:

result.user = user.data 

But it doesnt come out what I need. I am wondering if I can use a for loop such as

for (var i = 0; i < result.length; i++) {
  result.user = user.data;
}
Tenz
  • 535
  • 2
  • 7
  • 27
  • 1
    If you're modifying it in this way, it isn't JSON. JSON is a *textual notation* for data exchange. [(More.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Dec 05 '16 at 18:47

3 Answers3

3

You're close ...

for (var i = 0; i < result.length; i++) {
  // result.user = user.data;
  result[i].user = "user " + (i + 1);
}

Essentially, result is an array of objects; you need to tell it which one to reference when accessing the internals.

rfornal
  • 5,072
  • 5
  • 30
  • 42
1

yes use index of array . since you want 1 for 0th element so add 1 to index. forEach will iterate over each array element . where a is the element and index is ath element index.

var json={result: [ { "id": "1", "name": "name 1" }, { "id": "2", "name": "name 2" }, { "id": "3", "name": "name 3" } ] };
json["result"].forEach(function(a,index){
  a["user"]="user"+(index+1);
})
console.log(json);
Mahi
  • 1,707
  • 11
  • 22
0

First you need to put this json in a variable, then you can interate the object acessing the result array.

var object = {result: 
       [ 
         { 
           "id": "1",
           "name": "name 1",
           "user": "user 1"
          },
          { 
           "id": "2",
           "name": "name 2",
           "user": "user 2"
          },
          { 
           "id": "3",
           "name": "name 3",
           "user": "user 3"
          }
      ]
    };


for (var i = 0; i < object.result.length; i++) {
  object.result[i].user = "user " + i;
}

console.log(object);