0

Here is my JSON file below. Each object in the array belongs to an Id. So the first object would be #one, second object would be for #two. and so on. I can not figure out how to write this in JavaScript. How can I target which array number[1] with object[1] appends to #two for example? Also I need to delete the first line of the object which is the count line? Thank you!

so to get more into details. I was given an assignment, where I have placed pictures in the html and underneath the pictures, each object in the json file(description for the pictures) is supposed to go underneath it. I am new wtih json and ajax :( so the ids #one, #two... were just examples. There would be 6 ids. one for each object.

[
  [
    {
    "count": "80",
    "countTxt":"Buyer logins",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"523"
    },
    {
    "count": "233",
    "countTxt":"Searches",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"628"
    },
    {
    "count": "533",
    "countTxt":"Views of our member pages",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"2,365"
    }
  ],
  [
    {
    "count": "80",
    "countTxt":"Total vists",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"412"
    },
    {
    "count": "53",
    "countTxt":"Unique visitors",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"731"
    },
    {
    "count": "1:12 min",
    "countTxt":"Total time spent on page",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"784.2 mins"
    }
  ]
]
user3730179
  • 121
  • 4
  • 14

4 Answers4

1

You have an array containing arrays which contain objects. They don't appear to have those IDs in them anywhere, and with names like #one, #two, and such, it's awkward to assign those (you basically have to have a list of names waiting to be assigned).

The work itself is relatively simple once you have that list:

  1. Parse the JSON into an object graph via JSON.parse.

    var outerArray = JSON.parse(jsonText);
    
  2. Create a blank object you can save the named objects to as properties, like a map:

    var map = {};
    
  3. Type in your list of IDs as an array:

    // This assumes no more than 99 elements
    var ids = [
        "#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
    ];
    
  4. Have an index variable that starts with 0.

  5. Loop through the outermost array; you have lots and lots of options for how to do that, I'd probably use forEach:

    outerArray.forEach(function(nestedArray) {
       // ...more code here
    });
    
  6. Inside that loop, loop through the objects in the nested array:

    outerArray.forEach(function(nestedArray) {
       nestedArray.forEach(function(object) {
           // ...more code here
       });
    });
    
  7. Inside the inner loop, add the current object to your map using the next available ID via your index variable:

    map[ids[index++]] = object;
    
  8. If you really want to, remove the count property from the object:

    delete object.count;
    

So putting it all together:

var index = 0;
var outerArray = JSON.parse(jsonText);
var map = {};
var ids = [    // This assumes no more than 99 elements
    "#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
];
outerArray.forEach(function(nestedArray) {
   nestedArray.forEach(function(object) {
        map[ids[index++]] = object;
        delete object.count; // Doesn't matter whether this is before or after the line above
   });
});

Notes:

  • It's going to be really awkward to access those objects with IDs like #one and such, but I assume you have a reason for it. You do map["#one"] and such to get at the objects.

  • If you don't have to delete the count property, don't bother.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

First, you might want to ask yourself if your current way of formatting the data is appropriate. Currently, your data is formatted like this:

var jsonObject = 
[
  [{},{},{}],
  [{},{},{}]
];

Where you have an outermost array, that contains two arrays, and the json data/javascript objects are then stored inside of those arrays. There probably isn't a need for the outermost array, and it would simplify the way you access the data inside of your json object without it. So keep in mind that all the examples you get here on SO are going to refer to the JSON object as you presented it.

// List off all "countTxt" objects to demonstrate how to 
// iterate over a json object that contains nested
// arrays containing data. In your example, you have two arrays
// that each contain json data.


for (var i in jsonObject) {
    for (var j in jsonObject[i]){
        console.log(jsonObject[i][j].countTxt);
    }
}

The above loop will print out the following:

/*
    Unique visitors 
    Total time spent on page 
    Buyer logins 
    Searches 
    Views of our member pages 
    Total vists 
    Unique visitors 
    Total time spent on page 
*/

Warning: as T.J. Crowder pointed out, using for..in loops to access json data will come back to bite you, so using this type of for..in looping structure (above) isn't recommended in production code, but it serves as a simple demonstration how you use access notation [] to grab values from an array of data objects. To read up on some best practices, you can read T.J. Crowder's in-depth post on the subject here.

If you want to target a specific item in the jsonObject, you do so like this:

// Grab the second object in the data array:
var secondObjectInJsonData = jsonObject[1];
console.log(secondObjectInJsonData);
// secondObjectInJsonData -> [Object, Object, Object]

If you want to grab specific data inside the data array:

// Grab the second object, inside the first array of json data
var countTxtOfSecondObject = jsonObject[0][2].countTxt;
console.log(countTxtOfSecondObject);
// countTxtOfSecondObject --> "Views of our member pages"

To Delete an object, you can use the delete command

var someObject = jsonObject[1][2];
delete someObject.count;
console.log("someObject after 'count' has been deleted: ",  someObject);

Here is a JSFiddle to see all this code in action. Just open up the console in Chrome Developer Tools (in the Chrome browser) to see the output of all the console.log() statements.

Community
  • 1
  • 1
radiovisual
  • 6,298
  • 1
  • 26
  • 41
0

First of all, You should reformat your data, Try using JSON Editor Online, this shows a tree view of your data. Chrome Extension is available for this, Please check the Chrome web store. It's a really good practice.

I've reformatted your data and made it into something which is more readable. Take a look;

[
 {
   "count": "80",
   "countTxt":"Buyer logins",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"523"
 },
 {
   "count": "233",
   "countTxt":"Searches",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"628"
 },
 {
   "count": "533",
   "countTxt":"Views of our member pages",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"2,365"
 },
 {
   "count": "80",
   "countTxt":"Total vists",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"412"
 },
 {
   "count": "53",
   "countTxt":"Unique visitors",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"731"
 },
 {
   "count": "1:12 min",
   "countTxt":"Total time spent on page",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"784.2 mins"
  }
]

You can access the JSON data using jQuery.getJSON() method and use jQuery.each method to loop through the object. Try this out;

$.getJSON('data.json', function(data) {
   $.each(data, function(k) {
      console.log(data[k]);
   });
});

Check the console (ctrl+shift+j). enter image description here

  1. Now you can easily access the string. For eg; console.log('Count: ' + data[k]['count']); //Displays all the count.

Hope you got some idea, You can play around with the JSON object like this and correct me if I'm wrong. Thank You

sachq
  • 672
  • 7
  • 11
-1

You can access the properties as below

json[0][0]["count"]

If you want to delete a property use

delete json[0][0]["count"]

Fiddle http://jsfiddle.net/wa99rxgL/

Amal Hashim
  • 501
  • 3
  • 13