Get Children of JSON Elements using Javascript? [duplicate] - javascript

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]]);

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);

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

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
}))

Deleting an entire object in Javascript [duplicate]

This question already has answers here:
Why doesn’t deleting from a Javascript array change its length?
(6 answers)
Closed 8 years ago.
arr = [
{
id:1
},
{
id:2
}
]
This is an example object structure. I want to delete first object in this array.
delete arr[0];
Resulting structure is
[
{
undefined * 1
},
{
id:2
}
]
I have searched a lot and found that deleting an entire object will lead to dangling pointer problems. But i want resulting array to have only one object after deletion. Is there any other way to achieve this?
EDIT
How to do if the object is neither first nor last?
You need to create a shorter array instead. To remove the first element, just slice the array:
arr = arr.slice(1);
When the previous array is discarded the first element will also be discarded.
You could, as an alternative to Array.prototype.slice(), use array.prototype.shift(), which simply removes the first element of the array:
arr = [
{
id:1
},
{
id:2
}
];
console.log(arr); // [Object, Object]
arr.shift();
console.log(arr); // [Object]
References:
Array.prototype.shift().
Array.prototype.splice().
The only way to delete anything from an array is to resize it
arr = arr.slice(1)

How to sort a bi-dimensional javascript array? [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 8 years ago.
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];
title.forEach(function(title,i) {
global[title]=value[i];
})
I would like to sort the global array by value but I can't figure out how.
I precise I can't use any library jquery,underscore...
thanks !
the goal is to know what object has the less value.
a,b,c,d have values 50,1,4,29
I can sort values but how to know what's the name associated to this value ?
You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:
title.forEach(function(title,i) {
global[i] = {};
global[i][title]=value[i];
})
which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]
If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:
global.sort(function(a,b) {
return parseInt(a.value, 10) - parseInt(b.value, 10);
});
but this can't be applied to your array since all the keys are different.

Categories

Resources