How to determine the length of JSON containing object inside object [duplicate] - javascript

This question already has answers here:
How to efficiently count the number of keys/properties of an object in JavaScript
(19 answers)
Closed 6 years ago.
Is there any way to get the length from the following:
{
"11": {
"id": "456",
"uuid": "b596362a-b5bb-4n94-8fd5-1e9fh6fd877b",
"name": "Test",
"description": "Test"
},
"22": {
"id": "739",
"uuid": "c4ccbddf-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test2",
"description": "Test2"
},
"33": {
"id": "737",
"uuid": "m4ccbddv-5177-482f-b5e8-cdd4f699e6b7",
"name": "Test3",
"description": "Test3"
}
}
The length should be 3. I tried to use JSON.stringify(data).length but this gives the length of the whole string.

In addition to above answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:
Object.keys(jsonArray).length;
You can use following function
function getJsonItemLength(item) {
if (typeof item !== undefined && varNotNull(item) && item) {
if (Array.isArray(item)) {
return item.length;
} else if (typeof item === 'object' ) {
return Object.keys(item).length;
} else if (typeof item === 'string' ) {
return item.length
} else {
return 0;
}
}
return 0;
}

using Object.keys you get the list of keys (in an array) so you could:
Object.keys(obj).length

If you're asking about the length of an associative-array-like object, that's your answer: Length of a JavaScript object
Or to save you the click:
Object.keys(myObj).length;

Related

Remove empty Object from JSON arrays [duplicate]

This question already has answers here:
Remove Object From Array if the value is empty in name and value pair js
(3 answers)
Closed 2 years ago.
I am trying to remove this empty key value pair object from this JSON array but it I am unable to figure out on how to do it.
I tried this:
var array = {
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"},
{"lang":"German","value":""}
]
}
var result = array['title'].filter(function(x){return x.length});
This gives the following output:
{
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"},
{"lang":"German"}
]
}
Output expected:
{
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"}
]
}
Change your filter to look for an empty string in the value property:
var array = {
"title": [{
"lang": "English",
"value": "yes"
},
{
"lang": "Spanish",
"value": "no"
}, {
"lang": "German",
"value": ""
}
]
}
var result = array['title'].filter(x=>x.value !== "");
console.log(result);
You should do something like this.
array['title'].filter( element => element.value )
You aren't specifying what it's looking for for each element.
Try changing your filter function to check if the value exists and has a length greater than 0:
function(x) { return x.value && x.value.length > 0 }

How do I check if some object is not present in an array? [duplicate]

This question already has answers here:
Check if object value exists within a Javascript array of objects and if not add a new object to array
(22 answers)
Closed 5 years ago.
I have an array of objects like
[
{
"name": "Name 1",
"id": "1245"
},
{
"name": "Name 2",
"id": "9788"
},
{
"name": "Name 3",
"id": "5694"
},
{
"name": "Name 4",
"id": "4523"
},
{
"name": "Name 5",
"id": "4567"
}
]
I need to check if the array contains an object with an ID (let's say "1111"). If ID not found in any of the objects inside array, then place the new object(e.g., {"name":"Test 0","id":"1111"}) at the beginning of the array.
PS: Is there methods other than array.unshift(newObj), to achieve the goal?
Edit: Okay. I did tried using array.indexOf(), but it seems like it only works with values not objects. I also try looping through the array, but didn't worked too. I cannot use ES6.
Without ES6 and assuming your object is named users you can conditionally add one if it doesn't exist like this:
function addUser(name, id) {
users.forEach(function(user) {
if (user.id === id) {
return user;
}
});
var newUser = {"name": name,"id": id}
users.unshift(newUser);
return newUser;
}
Using reduce
function hasId(array, id){
return array.reduce(function(sum, element){
return sum || element.id === id;
}, false);
}
if(hasId(array, 1111)){
array.splice(0, 0, newElement);
}
There are 1000 ways to do this. This solution works with es5, it isn't too efficient because it runs through the entire array. The fastest way is to do it in a for-loop, then return on the first found, but this looks prettier.
Using for loop
function hasId(array, id){
for(var i=0; i<array.length;i++){
if(array[i].id === id){
return true;
}
}
return false;
}
if(hasId(array, 1111)){
array.splice(0, 0, newElement);
}
This is the fastest method, it stops as soon as the first id is found

Javascript - delete object from JSON array [duplicate]

This question already has answers here:
Find and remove objects in an array based on a key value in JavaScript
(14 answers)
Closed 5 years ago.
I would like to delete an object from a JSON objects array.
Here is the array:
var standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
For example how can I delete the object whose key is "Q": "Drinks" ?
Preferably of course without iterating the array.
Thanks in advance.
You have to find the index of the item to remove, so you'll always have to iterate the array, at least partially. In ES6, I would do it like this:
const standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
const index = standardRatingArray.findIndex(x => x.Q === "Drinks");
if (index !== undefined) standardRatingArray.splice(index, 1);
console.log("After removal:", standardRatingArray);

NodeJS: break Array.some loop [duplicate]

This question already has answers here:
Searching for items in a JSON array Using Node (preferably without iteration)
(6 answers)
Closed 5 years ago.
I have the following function that receives a JSON array templates and returns a JSON object.
The code executes the console.log. However, it always returns the null at the end of the function. Any ideas?
function getTemplate(templates, myId) {
Object.keys(templates).some(obj => {
if (templates[obj].id === myId) {
console.log('HELLO');
return templates[obj];
}
});
return null;
}
template array
[
{
"id": 80,
"name": "template 1"
},
{
"id": 81,
"name": "template 2"
}
]
However, it always returns null.
Here is working example,
use .find instead of .some. We always expect to get one object.
function getTemplate(templates, myId) {
return templates.find(template => template.id === myId);
}
var array =
[
{
"id": 80,
"name": "template 1"
},
{
"id": 81,
"name": "template 2"
}
]
console.log(getTemplate(array, 80));

How to iterate JSON objects with JSON objects in every object (JavaScript)? [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 multiple JSON objects which are have multiple JSON objects.
Now how do i iterate the Objects in deep.
My JSON structure is like below.
{
"phanim": {
"msg1": {
"data": "Hii ra..",
"date": "Sep 9",
"sender": "Phani",
"type": "text"
},
"msg2": {
"data": "How r u?",
"date": "Sep 9",
"sender": "Phani",
"type": "text"
}
}
}
Probably a recursive function - check if the typeof the current iterated property is an object, if so, iterate that!
var iterateObj = function(obj) {
for (var key in obj) {
if (typeof obj[key] === "object") {
iterateObj(obj[key]);
} else {
console.log(obj[key]);
}
}
}
Note: this won't work if one of your properties is an array - you'll need an additional check and logic for that.

Categories