So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
Answer from Crozin on Stack OverflowSo why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
Whether you choose the first or the third option depends on your use case. If you are modeling many different instances of the same type of thing, choose the first. For example, you have a list of people. If you are modeling many different attributes of one thing, choose the third. You can have repeated keys in the first format, but not in the third.
The second option is terrible, and I've yet to find an appropriate use case for it. The reason it's terrible, in addition to being more verbose, is that for single-level JSON, it breaks most libraries' automatic conversion to a dictionary/map. For deeply-nested JSON, it breaks the XPath-like query interface.
This makes it a pain to work with. And if you don't know your keys at compile time, you will want a dictionary or XPath interface, because you won't be able to convert it to a class. It may not seem like a big deal now, but the longer you have a data format, the harder it will be to change.
You say these are key / value pairs. In that case, use #3: dictionary of key / value pairs.
If these are not key / value pairs, then don't call them "keys" and "values" and use #2, an array of dictionaries with arbitrary contents.
Structure #1 is just daft unless you need key / value pairs but also their order. Which you rarely do.
Videos
Array#map()
const data = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
console.log(data.user.map(u=>u.name));
You can iterate over an array using the map function which takes a callback, and return exactly which property you want from each user object inside the callback. You'll be left with an array of names.
const myObject = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
const names = myObject["user"].map((user) => {
return user["name"];
}
Lean towards option 1, as it's a more expected format.
Option 1 works with JSON as it's designed to be used and therefore benefits from what JSON offers (a degree of human readability, which is good for debugging, and straightforward parsing, which is good for limiting entire categories of bugs to begin with).
Option 2 begrudgingly adopts JSON and subverts many of the benefits. If you don't want human readability, use protobuf or something similar... AIWalker's "CSV"-like approach isn't terrible either. It is marginally better (readable) than splitting objects apart and recombining them. But, this is still not as good (readable) as using JSON "as designed".
Also bear in mind, your API responses are also likely going to be gzipped. Most of the repetition in option 1 will be quickly and transparently condensed over the wire.
As an aside, if you're moving a lot of data, also consider JSONL or paginated results. Pagination can be especially helpful for web clients, as it places natural pauses in the processing, providing a degree of "organic" protection against UI lockups.
A list of objects is easier to work with. You can use append, map, filter... All the nice things JS Arrays have which manual indexing doesn't. And there's no way to get out of sync, so that's an entire class of bugs gone.
If you're worried about efficiency:
- Measure (premature optimization is the root of all evil)
- Consider the list of lists trick AIWalker proposed
- Consider an outright binary format
- Make sure gzip is enabled
- Measure (it's worth saying twice)
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
You can use array#reduce
var data = [ { "id": "id1", "data": "text" }, { "id": "id2", "data": "text" } ],
result = data.reduce((r,{id,data}) => (r[id] = {data}, r), {});
console.log(result);
You could use Object.assigna and spread syntax ...b with Array#mapc for the new properties with destructuring assignmentd, computed property namese and short hand propertiesf.
Object.assign(...array.map(({ id, data }) => ({ [id]: { data } })))
aaaaaaaaaaaaa bbbccccccccc dddddddddddd eeee ffff
var array = [{ id: "id1", data: "text" }, { id: "id2", data: "text" }],
object = Object.assign(...array.map(({ id, data }) => ({ [id]: { data } })));
console.log(object);