making nested objects array and checking if the key exists in objs - javascript

I am trying to check if the keys exits in array of objects. I am getting false each time when I pass existing key to my function.
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(name) {
for (var i = 0, len = connect_clients.length; i < len; i++) {
if (connect_clients[i].key === name)
return true;
}
return false;
}
console.log(lookup('a'));
Is there anything wrong?

connect_clients[i].key refers to the actual property named key, not the keys of the object.
For this case, you can use Object.keys to get an array of keys of an object and use Array.prototype.some to make sure that at least one of the objects has the key. For example,
function lookup(name) {
return connect_clients.some(function(client) {
return Object.keys(client).indexOf(name) !== -1;
});
}

Use Object.keys() to get keys of an object.
var val = 'val';
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(keyName) {
var i;
for ( i = 0; i < connect_clients.length; i++) {
var keys = Object.keys(connect_clients[i]);
if(keys.indexOf(keyName) !== -1) {
return true;
}
}
return false;
}
console.log(lookup('a'));

Related

How to remove item from an array on condition using JavaScript

I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.
Actual array:
[
{
"href":"/client",
"methods":[]
},
{
"href":"/home",
"methods":
{
"type1":"GET",
"type2":"POST",
}
},
{
"href":"/about",
"methods":[]
},
{
"href":"/contact",
"methods":
{
"type1":"GET",
"type2":"POST",
}
}
]
Expecting result:
[
{
"href":"/home",
"methods":
{
"type1":"GET",
"type2":"POST",
}
},
{
"href":"/contact",
"methods":
{
"type1":"GET",
"type2":"POST",
}
}
]
This is the job for filter. however filter does not modify the existing array so you need to assign it to a different array/overwrite the current variable
a = a.filter(item => Object.keys(item.methods).length > 0)
Iterate over the object array and filter based on methods property length.
var obj = [...];
obj = obj.filter((val) => val.methods && val.methods.length !== 0);
In the case of methods, you can easily walk the object and then call delete on the keys with values that are empty.... or empty arrays. I expanded the answer to cover not only keys of methods where an array is empty, but all keys with what i would define as empty contents.
var l = [];
for (var i = 0; i < l.length; i++){
var keys = Object.keys(l[i]);
for ( var j = 0; j < keys.length; j++){
var value = keys[j];
// In your use case, you are only doing arrays so i coded it as such.
if (value.length == 0){
delete l[i][j];
}
}
}
If you want to expand it to cover a variety of cases such as empty string, empty arrays, empty maps, or null values you can defined a function to do that.
function isValueDeletable(value){
if (value == null) return true;
if (value == "") return true;
if (value instanceof Array && value.length == 0) return true;
if (value instanceof Map && Object.keys(value).length == 0) return true;
return false;
}
and apply that instead of the value.length == 0;
if (isValueDeletable(value)){ delete l[i][j]; }
Then l is modified to remove all keys with empty values.
enter var json = {};
var key = "giveitakeyvalue";
json[key] = null;
delete json[key];

Removing outer array object if an inner array meets a condition

I am dealing with a fairly complex object. It contains 2 arrays, which contain 3 arrays each of objects:
I'm trying to delete one of the history: Array[2] if one of the objects in it has username: null.
var resultsArray = result.history;
var arrayCounter = 0;
resultsArray.forEach(function(item) {
item.forEach(function(innerItem) {
if (innerItem.username == null) {
resultsArray.splice(arrayCounter,1);
};
});
arrayCounter++;
});
Looking through answers it's recommended to do something like:
resultsArray.splice(arrayCounter,1);
This isn't working in this situation because more than one of the objects could have username == null and in that case it will delete multiple history objects, not just the one that I want.
How do I remove only the one specific history array index if username == null?
splice is evil. I think using immutable array methods like filter might be easier to reason about:
x.history =
x.history.filter(function (h) {
return !h.some(function (item) {
return item.username === null
})
})
Go through all the histories, and do not include them in the filter if they have a username that is null.
My understanding was that you only want to delete the first outer array that has an inner array that has an object with a null username. Heres one solution closest to your current form:
var resultsArray = result.history;
var arrayCounter = 0;
var foundFirstMatch = false;
resultsArray.forEach(function(item) {
if (!foundFirstMatch) {
item.forEach(function(innerItem) {
if (innerItem.username == null && !foundFirstMatch) {
foundFirstMatch = true;
};
});
arrayCounter++;
}
});
if (foundFirstMatch > 0)
resultsArray.splice(arrayCounter, 1);
Other syntax:
var resultsArray = result.history;
var outerNdx;
var innerNdx;
var foundMatch = false;
for (outerNdx = 0; !foundMatch && outerNdx < resultsArray.length; outerNdx++) {
for (innerNdx = 0; !foundMatch && innerNdx < resultsArray[outerNdx].length; innerNdx++) {
if (resultsArray[outerNdx][innerNdx].username == null) {
foundMatch = true;
}
}
}
if (foundMatch)
resultsArray.splice(outerNdx, 1);
Update - here's how I'd do it now, without lodash:
thing.history.forEach((arr, i) => {
thing.history[i] = arr.filter( (x) => x.username !== null );
});
Previous answer:
I'd use lodash like this:
_.each(thing.history, function(array, k){
thing.history[k] = _.filter(array, function(v){
return v.username !== null;
})
});
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/n4sjjkwn/2/
You should write something like this:
var resultsArray = result.history.filter(function(item){
return !item.some(function(inner){ return inner.username==null; });
});
The foreach loop cant break in this way but a regular for loop can. This is working:
result.history.forEach(function(item) {
loop2:
for (var i = 0; i < item.length; i++) {
var innerItem = item[i];
console.log(innerItem);
break loop2;
}
});

How to check if all fields whose names are given in an array are non-null?

I have a javascript array which contains the name of fields in a record:
fields=["size", "Hold","drawn%" ,"expiry"]
I need to persorm an operation,if the value in ALL these fields is not null.
I can iterate the array and check a not-null condition on each element.
Is there a better way to handle this; wherein each member of the array has to be evaluated against a particular condition, and return a cumulative true or false.
fields.every(function(name, i) { return record[name] !== null; })
will return true if every field from fields in record is not null, and false otherwise.
Array.prototype.IsNull = function() {
var arr = this;
var isNull = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == null) {
isNull = true;
break;
}
}
return isNull;
};
var fields=["size", "Hold","drawn%" ,"expiry"];
var isNull = fields.IsNull();

find the object index using id in json

I have a json that contains many objects:
[Object, Object, Object, ... ]
Inside each object there is an object number and an id:
0: Object
id: "theObjectImLookingFor"
...
How can I find the object number (0) using the id "theObjectImLookingFor" in javascript?
Try this:
function someFunc(){
var objArr = [Object, Object, Object, ... ];
for(var i = 0; i < objArr.length; i++){
if(objArr[i].id == "theObjectImLookingFor")
return i;
}
return "No value matched";
}
This assumes there's only one property with a numeric name. This is a very strange way to store something you want to be able to look up. Why not give each object an obj_number property?
function find_object(json, str) {
for (var i = 0; i < json.length; i++) {
if (json[i].id == str) {
for (var key in json[i]) {
if (IsNumeric(key)) {
return key;
}
}
}
}
return false; // Not found
}

Finding my object inside JSON by its ID

[
{"ID":"5","Name":"Jay"},
{"ID":"30","Name":"Sharon"},
{"ID":"32","Name":"Paul"}
]
So I have this kind of JSON.
I need to easily supply the value for a required key.
For example:
30 would yield => "Sharon"
5 would yield => "Jay"
etc. What is the right way to do this?
Iterate the array and check if the ID matches
function getById(id) {
var O = null;
for (var i=0; i<arr.length; i++) {
if ( arr[i].ID == id ) return O = arr[i];
}
return O;
}
getById('30'); // returns {"ID":"30","Name":"Sharon"}
FIDDLE
or in newer browsers:
function getById(arr, id) {
return arr.filter(function(o) { return o.ID == id });
}
FIDDLE
Try a linear search:
var searchId = "30";
for(var i = 0; i < json.length; i++)
{
if(json[i].ID == searchId)
{
// Found it.
//
break;
}
}
If the IDs will be unique, and if you're going to need to do this frequently, then you may want to convert your collection to key/value pairs where the ID is the key.
var byId = data.reduce(function(res, obj) {
res[obj.ID] = obj;
return res
}, {});
Now you can simply use the ID to look up the object.
var target = byId["30"];
You could probably just write something to loop through it.
var data = [ {"ID":"5","Name":"Jay"},{"ID":"30","Name":"Sharon"}, {"ID":"32","Name":"Paul"} ];
for(var i in data){
if(data[i]["ID"] == 30){
return data[i]["Name"];
}
}
undersocre.js can find a object in collection by one line code
Reference: http://underscorejs.org/#find
Code:
var people = [
{"ID":"5","Name":"Jay"},
{"ID":"30","Name":"Sharon"},
{"ID":"32","Name":"Paul"}
];
_.find(people, function(person) { return person.ID === '5'; });
FIDDLE

Categories

Resources