Loop through array of nested objects to check empty string es6 - javascript

I have an array of nested objects:
const array =[
{
"id": 1,
"time": {
"timezone": "2021-09-22T05:36:22.484Z"
"city": "Perth"
"country:: "Australia
"date": "2021/10/10"
}
},
{
​"id": 2,
​"time": {
"timezone": ​"2021-10-22T03:25:26.484Z"
"city": ""
"country: "Americas"
"date": "2021/10/10"
}
},
{
​"id": 3,
​"time": {
"timezone": ​"2021-09-27T02:43:26.564Z"
"city": ""
"country: ""
"date": "2021/10/10"
}
}];
I want to check each value in the time object to see if there exists an empty string without having to have multiple || statements.
What I have tried using lodash:
if(array.find((k)=> _.isEmpty(k.timezone)) || array.find((k)=> _.isEmpty(k.city)) || array.find((k)=> _.isEmpty(k.country)) || array.find((k)=> _.isEmpty(k.date))) {
//do something
} else {
//do something else
}
This seems to do the trick but trying to find a succinct and cleaner way to do this as there could be more values in the time object, preferably in es6.

Check if .some of the Object.values of any of the time subobjects includes the empty string.
if (array.some(
k => Object.values(k.time).includes('')
)) {
// do something
} else {
// do something else
}

Related

Matching certain value in JSON Array using match() or find() in JavaScript

I'm looking for a function or method to overcome this issue
Here is the JSON Array
[{
"type": "radar",
"detail": [{
"subject": "sub1"
}, {
"subject": "sub2"
}]
}, {
"type": "bar",
"detail": [{
"subject": "sub1"
}, {
"subject": "sub2"
}]
}]
I'm hoping to identify the value of "type" which in this case would be "radar" and "bar",and match with the variable x。
Here's the code:
for(x in myarray)
{
if(myarray[x]['type']=="bar")
{
console.log("equal");
}
else
{
console.log("no result");
}
}
With this code,the result on the website console would be both "equal" and "no result",while I wish to print "equal" only.I understand the logic error in this code,but I couldn't figure out the correct way to fix it.
You can use Array.some for this which return true or false if one of the array element match with type "bar" then It will return true otherwise false
var data = [{
"type": "radar",
"detail": [{
"subject": "sub1"
}, {
"subject": "sub2"
}]
}, {
"type": "bar",
"detail": [{
"subject": "sub1"
}, {
"subject": "sub2"
}]
}]
if (data.some(val => val.type == "bar"))
console.log("Equal")
else
console.log("No record found");
let myArr = [
{ "type":"radar",
"detail": [
{ "subject":"sub1" },
{ "subject":"sub2" }
]
},
{ "type":"bar",
"detail": [
{ "subject":"sub1" },
{ "subject":"sub2" }
]
}
]
for(let x of myArr){
if(x.type === 'bar'){ console.log('equal')}
else { console.log('no result')}
}
In order to understand what went wrong with your code, first when you have a for loop, you need to have a let/var keyword as below:
for(let x of myArr)
Secondly, instead of using for..in loop, which it meant for looping property of objects, use for..of loop which meant for looping array.
Third, while looping myArr, each and every element x is an object and type is the property, so just use x.type to make the comparison.
Lastly, as others have mentioned, Array#some / Array#find is a better way to deal with finding existence of element in an array
Since the for loop runs for each object in the array, the first console log for equal is for matched type and second console log is for the unmatched type. So, to get only one console and to write more appropriate code, you can use Array.find() and then add a if-else block for that. Something like this:
var myarray = [ { "type":"radar", "detail": [{ "subject":"sub1" }, { "subject":"sub2" }] }, { "type":"bar", "detail": [{ "subject":"sub1" }, { "subject":"sub2" }] } ];
var match = myarray.find(({type}) => type === "bar");
if(match) {
console.log("equal");
} else {
console.log("no result");
}

How to change value of JSON using for loop/ foreach?

I've tried to change the value of json depending on key, but my loop not work
here's the code:
var duce2 = [{
"pages": "foo1",
"hasil": ""
},
{
"pages": "foo2",
"hasil": ""
},
{
"pages": "foo3",
"hasil": ""
},
{
"pages": "foo4",
"hasil": ""
},
{
"pages": "foo5",
"hasil": ""
},
{
"pages": "foo6",
"hasil": ""
}
];
for (let key in this.duce2) {
console.log("jalan ga fornya");
if (this.duce2[key].pages == 'foo2') {
console.log("jalan ga ifnya");
this.duce2[key].hasil = '1';
}
}
console.log(duce2);
did i doing something wrong with the code above? the console.log doesn't appear on for and if
EDIT : my chrome dev console just showing this
I am not sure why you use "this.duce2" in your code.
However, some useful advices :
variables should be declared using the least permissive scope. Instead of declaring the array with "var", you should prefer "const"
arrays should not be traversed using the for...in construction (which is for object properties). Instead, you should prefer to use the forEach method.
The result would be:
const duce2 = [ ... ];
duce2.forEach((elem) => {
if (elem.pages === 'foo2') {
elem.hasil = '1';
}
});
Use duce2 instead of this.duce2,
You can iterate like this.
for (var key in duce2) {
if (duce2.hasOwnProperty(key)) {
if(duce2[key].pages=='foo2'){
//your code ,what needs to be done.
}
}
}
The for/in statement loops through the properties of an object.
Hope it helps..!

JavaScript Remove Object From Array Based on Child Property

Using vanilla JavaScript (supported by the latest version of Chrome, don't worry about IE) and/or lodash/underscore but no jQuery how can I take this array:
[
{
"id": 1,
"places": {
"city": "boston"
}
},
{
"id": 2,
"places": {
"city": "new york"
}
}
]
...and remove the entire object that has a city of "boston":
[
{
"id": 2,
"places": {
"city": "new york"
}
}
]
Please keep in mind this array could have dozens of entries. Thank you!
http://plnkr.co/edit/JW3zd6A7OcmihM4CTh1D?p=preview
One of the ways you can do this is by using filter. For example:
var dataWithoutBoston = data.filter(function (el) {
return el.places.city !== "boston";
});
And to make it reusable, you can have a function like this:
function removeFromCity(data, name) {
var result = data.filter(function (el) {
return el.places.city !== name;
});
return result;
};

What is wrong in sort function, need improvements also

I hava a json object have some records, and I need to sort the object,
code:
var data = [
{
"MRData": {
"StandingsTable": {
"StandingsLists": [
{
"season": "2014",
"round": "5",
"DriverStandings": [
{
"position": "2",
"positionText": "1",
"points": "100",
"wins": "4",
"Driver": {...},
"Constructors": [...]
},
{
"position": "1",
"positionText": "2",
"points": "97",
"wins": "1",
"Driver": {...},
"Constructors": [...]
}
]
}
]
}
}
}
];
//What is Wrong in This function
function sortObj(obj, nextObj){
console.log(obj.position);
console.log(nextObj.position);
if(obj.position < nextObj.position){
return obj;
}else{
return nextObj;
}
}
var driverObjects = data[0].MRData.StandingsTable.StandingsLists[0].DriverStandings;
console.log(driverObjects);
var sortedData = driverObjects.sort(sortObj); //Do I need to use any other functions //like filter, map ?
console.log(sortedData);
Fiddle
Have a look at the console, to use the output, I was excepting the output like
[Object { position="1", positionText="1", points="100", more...}, Object { position="2", positionText="2", points="97", more...}]
But it is displaying same as passed function.
please correct the function mistakes.
Give me an optimized or more standard code implementation
sortObj() should return either positive value or negative value or 0
You can do like this..
function sortObj(obj, nextObj){
console.log(obj.position);
console.log(nextObj.position);
return nextObj.position-obj.position
}
The callback function for the sort method should return -1 (when the second parameter is greater), 0 (when both parameters are equal) or 1 (when the first parameter is greater)
Array.prototype.sort()
so you need this sort function:
function sortObj(obj, nextObj){
return obj.position - nextObj.position;
}

Using jQuery $.each with Json erroring with 1 result

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.

Categories