Converting JSON string with multiple arrays to Javascript object [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json file in a structure like this one:
{
"items":[
{
"username":"abc",
"orderID":"1234",
"commentHistory":[
{
"comment":"Comment Date: 2016/12/09 13:44:23"
},
{
"comment":"Failed: 2016/12/08 11:42:12"
}
],
.........
}
]}
Where an array "items" is storing the data and there is another array inside to store the comment history.
I know I can get the data using JSON.parse, like the example from W3School (http://www.w3schools.com/js/tryit.asp?filename=tryjs_json_parse).
However, the example only including one array in it. So if I want to get the data inside the second array, ie: comment inside comment history... how the syntax would look like if I want to access the data of an array inside another array? Thank you so much.

Not much syntax at all. This code should work for any number of comments within a given history.
JSON.parse(jsonString).items[0].commentHistory.map(function (e) {
return e.comment
})
Here's a snippet so you can see for yourself:
var data = {
"items":[
{
"username":"abc",
"orderID":"1234",
"commentHistory":[
{
"comment":"Comment Date: 2016/12/09 13:44:23"
},
{
"comment":"Failed: 2016/12/08 11:42:12"
}
],
}
]}
console.log(data.items[0].commentHistory.map(function (e) {
return e.comment
}))

Related

Can I set Javascript object keys based on a variable, e.g index of a loop? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 12 months ago.
I'm looping over an array, getting data from an API on each iteration.
I want to pass data from all iterations of the loop from my express server to the browser using res.json(), so I want to create an object that contains an object of data for each API call, as well as some other key-value pairs that will be created depending on what is returned.
e.g.
on loop index 0:
artist0:
{
data: 'data',
moreData: 'more-data'
}
on loop index 1:
artist1:
{
data: 'data',
moreData: 'more-data'
}
etc
I would use an array, but one of the calls (at random) will result in another key value pair,
e.g.:
correctAnswer: 'a_url.com'
this will be generated by one of the earlier API calls at random, so I cant get it at the other end using its array index.
I need the key 'correctAnswer', so I also need each object of API data to be identified by which API call it came from.
Short question: Can I name keys based on variables?
As always, your kind help is greatly appreciated :-)
You could solve this by not putting artists directly in the object, like this, using a array inside a single attribute of the object:
{
"artists": [
{
"data": "data",
"moreData": "more-data"
},
{
"data": "data",
"moreData": "more-data"
}
],
"correctAnswer": 3
}
Or alternatively, if you really want a dynamic key you can use
{
[`artist${artistIndex}`]: {'data': 'data'}
}

Why when I update a nested array in the parent array and other children receive the same value? [duplicate]

This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 1 year ago.
I faced a strange situation when I tried to create an array of arrays via fill and then I tried to add some value to the first child I saw all other nested arrays receive this value as well.
I have an idea why it could happen. It looks like the fill property uses the same object of all 3 nested 'places\items' and now each item is the reference to the single Array.
Also, I tried to use the .fill(new Array()) instead of the literal expression but I had the same result.
I'm not sure if I'm right so fix me, please, if I missed something. Thanks
// an amount of the required output arrays
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill([]);
cols[0].push({id: 1})
The expected result:
[
[
{
"id": 1
}
],
[],
[]
]
the actual result:
[
[
{
"id": 1
}
],
[
{
"id": 1
}
],
[
{
"id": 1
}
]
]
P.S. What is the right way to achieve the result I want to have? Should I just use the for cycle and populate the parent array via the children or maybe some nicer way exists?
From the fill docs at MDN:
If the first parameter is an object, each slot in the array will reference that object.
This means that you get an array of references to the same array (which is an object as well).
As to how to do it in a nicer way... that depends on what you want to achieve. Why do you need the array of arrays? Will they all have a fixed length?
Arrays are passed down by reference this makes it not that great for the fill method. Though you can fill it with a placeholder value and then map those to an array.
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill('').map(() => []);
cols[0].push({id: 1})
console.log(cols);
EDIT: As pointed out in the comments, a better solution:
const requiredArrays = 3;
const cols = Array.from({length: requiredArrays}, () => []);
cols[0].push({id: 1})
console.log(cols);

Get Children of JSON Elements using Javascript? [duplicate]

This question already has answers here:
How to select nth item inside the object
(2 answers)
Closed 2 years ago.
If I were to have a Json file that looked something like this:
{
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
and I wanted to get the value of the third number (three) using JavaScript. Instead of doing...
jsonObject.numbers.thirdnum
Is there a way I can select that value using some sort of children or index method? for example something kind of like this...
jsonObject.numbers.children[2]
First you have to convert your JSON to JavaScript:
const object = JSON.parse(string_of_json);
Then you can get an array of an objects properties, keys, or both with the appropriate methods on the Object class.
Object.keys(object.numbers)[2];
Object.values(object.numbers)[2];
Object.entries(object.numbers)[2];
Since order isn't guaranteed, this isn't generally useful unless you want to do something to every item item you get back.
If you want to access them by position then you should usually write your orignal JSON to use an array instead of an object.
{
"numbers": [ "one", "two", "three", "four", "five" ]
}
You can use Object.values to convert the values to an array and attach the index.
obj = {
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
console.log(Object.values(obj.numbers)[3])
After you parse JSON it became Object, so
const obj = {
"numbers": {
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
};
console.log(obj.numbers[Object.keys(obj.numbers)[2]]);

How to create a JSON object with duplicate keys [duplicate]

This question already has answers here:
Sailsjs Mysql ORM multiple query on the same table field
(2 answers)
Closed 7 years ago.
I'm working on a SailsJS project and I need to create a json object for my ORM search to work, This is how the search should be performed
Venue.find({
is_published: true,
restaurant_services: {
contains: '"delivery":"1"',
contains: '"takeout":"1"'
},
restaurant_specialties: {
contains: '"breakfast":"1"',
}
}).exec
So as you may see the JSON object inside the Find() is the one O need to create and the values inside has duplicate keys.
You can't. Your should try using something like this instead:
Venue.find({
is_published: true,
restaurant_services: {
contains: ['"delivery":"1"','"takeout":"1"']
},
restaurant_specialties: {
contains: [ '"breakfast":"1"' ]
}
}).exec
Or this:
Venue.find({
is_published: true,
restaurant_services: {
contains: {"delivery":"1","takeout":"1"}
},
restaurant_specialties: {
contains: { "breakfast":"1" }
}
}).exec
The problem is that the {... } Jason represents a map and therefore can't have duplicate keys. Although duplicate keys are strictly not Syntax errors but they are going to able also not going to work as expected with browsers or json libraries. If you can't change the syntax for your json object then you will have to produce that json by string concatenation instead of the normal Javascript type approach.

Javascript multi-dimensional array to and from JSON (jQuery?)

I have a Javascript problem where I need to be able to store data like follows:
MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..)
The main array has 10 sub arrays, these sub arrays then contain any number of JavaScript Objects.
I need an efficient way of storing the data this way and need to know how to parse to JSON/decode back to a manageable structure in Javascript.
The reason for this structure is because the Java program I'm communicating with uses this structure.
I'm able to use jQuery if that makes any difference.
Your structure appears to look like this
var myVariable = [
[
{ }, { }, { }
],
[
{ }, { }, { }
]
]
This can be JSON stringified. It yields "[[{},{},{}],[{},{},{}]]"
Use JSON.stringify and JSON.parse, respectively.

Categories

Resources