How to get names of nested Json objects with javascript [duplicate] - javascript

This question already has answers here:
Getting the object's property name [duplicate]
(13 answers)
Closed 7 years ago.
Sometimes there are a few values in JSON which are not present as name value pairs but as only names and then their properties and below for example in the JSON below objectOne, ObjectTwo and objectThree. The problem is that there names keep on changing how can I extract them if I don’t know in advance what these names are going to be? But the data structure will be same
{
"Number of objects": 3,
"Devices": {
"objectOne": {
"name": "10",
"name1": "50"
},
"objectTwo": {
"name": "20",
"name1": "30"
},
"objectThree": {
"name": "40",
"name1": "80"
}
}
}

You can try to use Object.keys method.
Sample :
var yourJson = {
"Number of objects": 3,
"Devices": {
"objectOne": {
"name": "10",
"name1": "50"
},
"objectTwo": {
"name": "20",
"name1": "30"
},
"objectThree": {
"name": "40",
"name1": "80"
}
}
}
var keys = Object.keys(yourJson.Devices); // Array with "objectOne", "objectTwo" and "objectThree"
UPDATE :
Then you can access to objectTwo this way :
var objectTwo = yourJson.Devices[keys[1]];
If you need to iterate through all, this is better :
for (var key in keys) {
// key = "objectOne", then "objectTwo", then "objectThree"
var objectN = yourJson.Devices[key]; // the device object
}

Related

Javascript - convert array to stringify format [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Serializing an object to JSON
(4 answers)
Closed 4 months ago.
I have this array:
array = [
{
"name": "name",
"value": "Olá"
},
{
"name": "age",
"value": "23"
},
{
"name": "isVisible",
"value": "1"
}
]
And i need to convert it to this stringified format:
"{\"name\":\"Olá\",\"age\":123,\"isVisible\":true}"
I have made several attempts without luck.
My last attempt was this one:
array = array.map((p) => {
return Object.values(p).join(':').replace(/\[/g, '{').replace(/]/g, '}').toString();
}),
Any solutions?
Simply make a empty object, iterate over your array to populate that object, then JSON.stringify(obj) to get your result.
Like this:-
var obj = {};
array = [
{
"name": "name",
"value": "Olá"
},
{
"name": "age",
"value": "23"
},
{
"name": "isVisible",
"value": "1"
}
]
for(let i of array) {
obj[i.name] = i.value;
}
const str = JSON.stringify(obj);
console.log(str);
/*
output : "{\"name\":\"Olá\",\"age\":123,\"isVisible\":true}"
*/

Get an adjacent value in JSON array if value is found [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
If I have this type of object returned in javascript (as a result of $get)
[
{
"id": "1",
"username": "john"
},
{
"id": "2",
"username": "bill"
}
]
How would I search for the username "john" and if it exists return his ID
Thanks
i.e.
$.get( baseURL + "users/")
.done(function( data ) {
var usernames = data.results;
});
Use find():
var array =[
{
"id": "1",
"username": "john"
},
{
"id": "2",
"username": "bill"
}
];
var id = array.find(k=>k.username=='john')?.id;
console.log(id);

Filter an array of objects so that no 2 objects are the same [duplicate]

This question already has answers here:
What is the recommended way to filter Objects with Unique property in the array in JS?
(4 answers)
Closed 3 years ago.
I have the following array. If the st and the ct are the same then the objects are considered to be the same. for example the 1st and the 3rd object have the same st and ct so the 3rd should be ignored(filtered out) of the final array. How do I filter this array so that no 2 objects are identical, preferably using the array.filter method? i have read the documentation I just dont get how to express what i want as the conditional for the filter function.
[{
"st": "2012",
"id": "43",
"ct": "1",
"sd": "2"
},
{
"st": "2015",
"id": "45",
"ct": "2",
"sd": "2"
},
{
"st":"2015",
"id": "45",
"ct": "2",
"sd": "1"
},]
You can do:
let uniqueArray = array.filter((o, i, self) => {
return self.findIndex(z => z.ct === o.ct && z.st === o.st) !== i;
});
var objects = [{
"st":"2012",
"id": "43",
"ct": "1",
"sd": "2"
},
{
"st":"2015",
"id": "453",
"ct": "2",
"sd": "2"
},
{
"st":"2012", // this is a duplicate
"ct":"1"
}
];
// Using a Set to keep track of uniqueness avoids iterating through the
// entire array with methods like .findIndex()
var knownKeys = new Set();
var key;
var uniqueObjects = objects.filter(function(obj) {
key = obj.st + obj.ct;
return !knownKeys.has(key) && knownKeys.add(key);
});

How to loop through an array of object literals, concatenating values that share a duplicate id? [duplicate]

This question already has answers here:
Merge JavaScript objects in array with same key
(15 answers)
Closed 4 years ago.
I need an efficient way to loop through an array of object literals and concatenate values within the objects that have duplicate IDs.
Is there a more elegant way of doing this versus having multiple for loops nested within each other?
For example, this is the data I am given:
{ "theList": [
{
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "123"
},
{
"id": 102,
"name": "Sunnyvale Park",
"number": "456"
},
{
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "789"
]};
The expected result should be:
{ "theList": [
{
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "123, 789"
},
{
"id": 102,
"name": "Sunnyvale Park",
"number": "456"
]}
You can use reduce
let obj = [{ "id": 101,"name": "Bubbles' Cat Farm","number": "123"},{"id": 102,"name": "Sunnyvale Park","number": "456"},{"id": 101,"name": "Bubbles' Cat Farm","number": "789"}];
let op = obj.reduce((out,inp)=>{
if(out[inp.id]){
out[inp.id].number += ', ' + inp.number;
} else {
out[inp.id] = inp
}
return out
},{})
console.log(Object.values(op))
using reduce and the findIndex function you will be able to achieve what you want.
const array = [{
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "123"
},
{
"id": 102,
"name": "Sunnyvale Park",
"number": "456"
},
{
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "789"
}
]
const result = array.reduce((accum, cv) => {
const index = accum.findIndex(item => item.id === cv.id);
if (index === -1) {
accum.push(cv);
} else {
accum[index].number += ", " + cv.number;
}
return accum;
}, [])
console.log(result)
If number is the only key which has distinct values, then you could do something like this using reduce:
const input = {"theList":[{"id":101,"name":"Bubbles' Cat Farm","number":"123"},{"id":102,"name":"Sunnyvale Park","number":"456"},{"id":101,"name":"Bubbles' Cat Farm","number":"789"}]}
const merged = input.theList.reduce((acc, {id,name,number}) =>{
acc[id]
? acc[id]["number"] += ", " + number
: acc[id] = {id,name,number};
return acc
},{})
const final = { "theList": Object.values(merged) }
console.log(final)
Create an accumulator with each unique id as key and the object you need in the final array as value like this. Then concatenate the number when a id already exists in the accumulator, else add a new key to the accumulator.
{
"101": {
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "123, 789"
}
}
Then use Object.values to get only the values of theList in an array.
You can make your container a dictionary where the key is the ID and eachvalue is an empty list. So when you loop through the original data. If the key doesnt exist, create a list with one item. If the key does exist already, just append the value to the list.

Sort an array of objects based on a numeric key given as String values [duplicate]

This question already has answers here:
Why doesn't this arrow function work in IE 11?
(5 answers)
Javascript: Converting String to Number?
(4 answers)
Sort array of objects by string property value
(57 answers)
Closed 4 years ago.
I have an array with key-value pairs, array columns are id and name. I want to sort this array by id.
The id column value is of type string type but I want to sort them as numeric values also should work on IE
Here is my code:
var items = [{
"id": "165",
"name": "a"
},
{
"id": "236",
"name": "c"
},
{
"id": "376",
"name": "b"
},
{
"id": "253",
"name": "f"
},
{
"id": "235",
"name": "e"
},
{
"id": "24",
"name": "d"
},
{
"id": "26",
"name": "d"
}
];
console.log(items.sort((a, b) => Number(a.ID) - Number(b.ID)))
Though the order does change it doesn't change as expected also in IE an error is thrown.
Now you can do it with pure JS, using the sort method..
var items = [
{
"id": "165",
"name": "a"
},
{
"id": "236",
"name": "c"
},
{
"id": "376",
"name": "b"
},
{
"id": "253",
"name": "f"
},
{
"id": "235",
"name": "e"
},
{
"id": "24",
"name": "d"
},
{
"id": "26",
"name": "d"
}
];
items.sort((a,b)=>+a.id>+b.id);
console.log(items);

Categories