简体   繁体   中英

JSON Objects in a JSON Array in javascript

I am playing around with JSON objects in JSON arrays. On click of a button, I push the json objects into a array like below:

jsonArray.push({
    columnNameProperty: columnName,
    columnValueProerty: columnValue,
    id: column.id

});

My resulted array looks like this:

[
 0:{
   columnNameProperty: "Name",
   columnValueProperty: "Nancy",
   id: "123"
 },
 1:{
   columnNameProperty: "Name",
   columnValueProperty: "Jene",
   id: "124"
 },
 2:{
   columnNameProperty: "Amount",
   columnValueProperty: "1000",
   id: "123"
 },
 3:{
   columnNameProperty: "State",
   columnValueProperty: "WA",
   id: "123"
 }
]

How do I modify this as I want to push items based on the id.

[
  "123" : {
      "Name" : "Nancy",
      "Amount" : "1000",
      "State" : "WA"
 },
  "124" : {
      "Name" : "Jene"
 }
]

Anyone could suggest me how to structure it in this format.

@Amy is correct, that is not in fact valid javascript. Arrays do not have keys. So your example

[
 0:{
   columnNameProperty: "Name",
   columnValueProperty: "Nancy",
   id: "123"
 },
 1:{
   columnNameProperty: "Name",
   columnValueProperty: "Jene",
   id: "124"
 }
]

really looks like this

[
     {
       columnNameProperty: "Name",
       columnValueProperty: "Nancy",
       id: "123"
     },
     {
       columnNameProperty: "Name",
       columnValueProperty: "Jene",
       id: "124"
     }
]

If your goal is to retrieve an element by id you could make a function that loops through the array, finds and returns the object with the given id.

Alternatively, you could create a hash map and access each values by its key. So for instance, given this object:

let map = {
  "123" : {
      "Name" : "Nancy",
      "Amount" : "1000",
      "State" : "WA"
 },
  "124" : {
      "Name" : "Jene"
 }
}

You could get the value of the key "123" by saying map['123']

Why do you have to use an array? For what you are trying to achieve you can set up a object and then just insert more objects into it.

var exampleObject={};

function onClick(){
exampleObject["123"]={"Name":"steve"}
}

I assume you are trying to use that approach to later find the right object in the array?

You can simply loop over the object and find it in there:

for (var obj in exampleObject){

   if(obj==="123"){
       //do something
   }
}

Was able to achieve the required format by creating HashMap/Object:

var id = column.id;
var mapObject = {}, editMap = {};
if(editMap.hasOwnProperty(id)){
    mapObject = editMap[id];
    mapObject[columnName] = grid[columnName];
    editMap[id] = mapObject;

}
else{
    mapObject[columnName] = [columnName];
    editMap[id] = mapObject;
}

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