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 }
Related
This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Adding a new array element to a JSON object
(6 answers)
Closed last month.
I have the following variable holding a json array.
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
I would like to add a property called "Id" to the above object inside data array. I expect to get something like;
{ "data": [ { "type": "Type1", "value": "MyValue", "id": "123" } ] }
How can I achieve this? I tried the following:
requestJson["data"][0]["id"] = '123';
But when I print requestJson["data"] I'm getting undefined. Would appreciate any help in appending the "Id" attribute to the object inside the array above. Thanks in advance.
You need to parse your string to convert it to an Object and after that you can manipulate the data attribute
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
const parsedObject = JSON.parse(requestJson)
parsedObject.data[0].id = 1
console.log(parsedObject)
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
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);
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;
Basically I am transforming a JSON result into html and using $.each it iterate through multiple keys. For example, I am pulling back facebook posts and iterating through the likes in that post.
The problem lies in the fact that when there are multiple "likes" everything works great! although when there is only 1 "like" the "source" key is removed from the result set and my javascript breaks because I expect it to be there. Any idea why the $.each is skipping a level for single nodes? The following is my code:
* JQUERY **
$.each(post.likes.item, function(i, like){
$(currentpost).find('div.cc_likes').append(like + ',');
console.log(like)
});
* JSON RESULT **
* Single Like
likes": {
"item": {
"source": {
"cta": "Mary Smith",
"url": "http:\/\/www.facebook.com\/",
"photo": {
"image": "https:\/\/graph.facebook.com\/"
}
}
},
Result in console:
Object
cta: "MaryAnn Smith"
photo: Object
url: "http://www.facebook.com/"
* Multiple Likes
"likes": {
"item": [
{
"source": {
"cta": "Bobby Carnes Sr.",
"url": "http:\/\/www.facebook.com",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
},
{
"source": {
"cta": "Jenna Purdy",
"url": "http:\/\/www.facebook.com\",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
},
{
"source": {
"cta": "Kevin Say",
"url": "http:\/\/www.facebook.com\",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
}
],
"count": "10",
"count_display": "10"
},
Result in console:
Object
source: Object
cta: "Kevin Smith"
photo: Object
url: "http://www.facebook.com/"
Since $.each() needs an array or array like object as argument, before using the object post.likes.item check if it is an array of not.
Following code will always pass an array to jQuery -
$.each([].concat(post.likes.item), function(i, like){
$(currentpost).find('div.cc_likes').append(like + ',');
console.log(like)
});
Explanation
[] is an empty array in JavaScript. Every array in JavaScript has a concat method.
[].concat(obj) concats obj to the empty array and returns an array.
if obj is not an array, result is [obj] which is an array with one item.
if obj is an array, then result is a deep copy of obj which is already an array.
More about concat method
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
That is the jquery code being run on your JSON return. What's happening is, when you are looking at multiple results, it is looping through the array, return each base level object. However, when you are running it on a single return, it is looping through the object properties(in this case, "source"), and returning the value of that property.
You have two choices here. You can either make sure single items are still put in an array, or you can do a check for single items on the client side. The way Moazzam Khan suggests is the best way to do it in most cases.