Find index of object in javascript using its property name - javascript

I want to find Index of javascript array of objects using objects property name. My code is :-
const checkbox = [{'mumbai': true},{'bangalore': true},{'chennai': true},{'kolkata': true}];
How can i find index of chennai? Can i acheive using lodash?

You can use .findIndex()
const checkbox = [
{'mumbai': true},
{'bangalore': true},
{'chennai': true},
{'kolkata': true}
];
const finder = (arr, key) => arr.findIndex(o => key in o);
console.log(finder(checkbox, 'chennai'));
console.log(finder(checkbox, 'kolkata'));
console.log(finder(checkbox, 'delhi'));

checkbox.map((v,i) => Object.keys(v).indexOf("chennai") !== -1 ? i : -1).filter(v => v !== -1)[0]
Will give you the index of "chennai", replace it with any other key to get a different index.
What this does is:
Map the array to an array indicating only indices which contain objects with the wanted key
Filter only the indices which you want
Get the first one (you can use the rest as well if there are multiple entries matching your search)
This works in every browser since it only uses .map() , Object.keys() and .filter()

Related

Retrieve all matching values from json array

I have a json array. I want to retrieve all "tag" values where listid=n;
[
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
I have found how to search an array for an individual value, but I can't seem to find anything on returning multiple values I require, as a json array.
You can first filter for the items you want, then map to get the specific property you are after.
let a = [
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
let n = "2"
let found = a.filter(item => item.listid === n).map(item => item.tag)
console.log(found)
This is assuming you want to do this in javascript

How to check if the key exist in json array?

I have a json object, the structure of which is given below. I try to find if the key (for eg: 1 & 2) exist or not by myArray.includes('1') but it doesn't work. Is looping through the array the only way to check if attribute exist or not?
[{"1": [{}]},{"2": [{}]}]
The way to check if an object with a particular property exists or not would be to filter the objects by verifying if they have given property or not.
To check if an object contains a property you could use Array.prototype.includes on the list of keys obtained through Object.keys. Here's an example:
var data = [
{"1" : []},
{"2" : []}
];
// Count of objects containing a given key.
console.log(data.filter(t => Object.keys(t).includes("1")).length);
console.log(data.filter(t => Object.keys(t).includes("2")).length);
console.log(data.filter(t => Object.keys(t).includes("3")).length);
You have to loop through all of the elements in the Array and check if the key exists in each of those Objects.
arr.some(e => e.hasOwnProperty('1'));
You can use Array.some() which tests whether at least one element in the array passes the test.
const has1 = myArray.some(obj => obj.hasOwnProperty(“1”)); // Returns a boolean
const has2 = myArray.some(obj => obj.hasOwnProperty(“2”)); // Returns a boolean
You can use use some() and Object.prototype.hasOwnProperty()
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
let arr = [{
"1":[{}],
"2":[{}]
}]
let checkOne = arr.some(x => x.hasOwnProperty('1'));
let checkThree = arr.some(x => x.hasOwnProperty('3'));
console.log(checkOne) //true
console.log(checkThree) //false
You can try forEach to loop the keys of object and check if yours is there.
var obj = yourobject;
var mykey = 0;
Object.keys(obj).forEach(function(k){
if(k == mykey){
...
}
});

Convert string parameter to an array of one element

I wrote a function which has to support two types of a paramter names for a list of values. Internally it deals with the parameter as an array.
A single name is given as string and multiples names are given as an array of strings.
// simplified example
let doSome = names => names.map(name => name.toUpperCase())
names(['Bart', 'Lisa'])
// [ 'BART', 'LISA' ]
names('Homer')
// TypeError: names.map is not a function
I found a solution using Array.of() in combination with flatten() which needs some babel configuration.
doSome = names => Array.of(names).flatten().map(name => name.toUpperCase());
Is there an idiomatic way in JavaScript to get an array without a type check?
You can use Array.concat(), since concat accepts both arrays and non arrays:
const names = (v) => [].concat(v).map(name => name.toUpperCase())
console.log(names(['Bart', 'Lisa'])) // [ 'BART', 'LISA' ]
console.log(names('Homer')) // ['HOMER']
Short solution:
[names].flat()
If names is an array, it will be left as-is. Anything else will be converted to an array with one element.
This works because .flat() only flattens one level by default.
If names is not an array, [names] makes it an array with one element, and .flat() does nothing more because the array has no child arrays.
If names is an array, [names] makes it an array with one child array, and .flat() brings the child array back up to be a parent array.
Alternative
This is more self-explanitory:
names instanceof Array ? names : [names]
This uses a simple ternary statement to do nothing to it if it is an array already or make it an array if it is not already.
You might not be able to implement it this way if you already have code depending on this function. Still, it would probably be cleaner to allow your function to accept a variable number of arguments with rest parameters.
It means you can call the function as names('Homer') or names('Bart', 'Lisa'):
function names(...args){
return args.map(name => name.toUpperCase());
}
console.log(names('Bart', 'Lisa')); // [ 'BART', 'LISA' ]
console.log(names('Homer')); // ['HOMER']
If you really want to call the function with an array as argument, you can use the spread syntax :
console.log(names(...['Bart', 'Lisa'])); // [ "BART", "LISA" ]
If you use it with a string, you'll get back an array of characters, though:
console.log(names(...'Homer')); // [ "H", "O", "M", "E", "R" ]
Why not just check if the input is an array or not using isArray()?
I made another solution using this approach, also I put a control inside the map() so this don't fail when the name argument is null or undefined.
const names = x => (Array.isArray(x) ? x : [x]).map(name => name && name.toUpperCase());
console.log(JSON.stringify( names(['Bart', 'Lisa']) ));
console.log(JSON.stringify( names('Homer') ));
console.log(JSON.stringify( names('') ));
console.log(JSON.stringify( names(null) ));
console.log(JSON.stringify( names([null]) ));
console.log(JSON.stringify( names([undefined, "Roger", "Bob", null]) ));
Maybe an maybe upcoming method of Array#flat would help in this case (works actually only in Chrome and FF).
const names = unknown => [unknown].flat().map(name => name.toUpperCase())
console.log(names(['Bart', 'Lisa']));
console.log(names('Homer'));

Cannot get/fetch keys from an array in javascript

I have an array object where there are key value pairs. I am trying to get the keys in that array using a loop but I am getting only 0. What is the problem with my code.
var strj = '{"name":"John","age":"30","cars":
[ {"type":"car", "year":"1998"},
{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type=='car');
Value of care
0:{type: "car", year: "1998"}
length:1
__proto__:Array(0)
Loop
for (var key in care){
if(care.hasOwnProperty(key)){
console.log(key)
}
}
care is a array type so you cannot do for (var key in care). You need to do for (var key in care[0]). This is because for (var key in care) will look for the key value in care and since it is a array it will always take 0 as a value in key(as you have only one object in array and its index is 0). That is why you got 0 in console.log.
var care =[{type: "car", year: "1998"}];
for (var key in care[0]){
if(care[0].hasOwnProperty(key)){
console.log(key)
}
}
care.forEach( ( singleCar ) => {
for ( var key in singleCar ){
console.log(key);
if( care.hasOwnProperty( key ) ){
console.log(key);
}
}
})
forEach will give you all the objects one by one. so you can check them.
As others have solved the issue, might i make a suggestion - Object.keys () gives an array of the keys for a given object. Since you are getting your filtered object and simply want its keys - the following will achieve that. Note that this is only using the code after you have filtered the original and have gained the "care" object.
As an aside, note that object.values() will give you an array of the values in a given object and object.entries() will give you arrays of the key / value pairing.
var care = {type: "car", year: "1998"};
var keys = Object.keys(care)
console.log(keys) // gives ["type","year"]
filter() method returns a Array of matches.
var care = myobj.cars.filter(c => c.type=='car'); // So, this returns an array.
care.forEach(element => {
console.log(Object.keys(element)); //Prints keys of each element
});
Well actually there is no problem in your code at all. But you just misunderstood the use of javascript filter. Javascript filter() creates new array that's why you are getting 0 as key. If you want to get only one matching element then find() is what you should use.
var strj = '{"name":"John","age":"30","cars":[{"type":"car", "year":"1998"},{"type":"van", "year":"1995"}]}';
var myobj = JSON.parse(strj)
var care = myobj.cars.filter(c => c.type == 'car'); // returns array
var care = myobj.cars.find(c => c.type == 'car'); // returns first matching object
var care = myobj.cars.findIndex(c => c.type == 'car'); // returns first matching index
Javascript filter() method => Read Here
Javascript find() => Read Here
Javascript findIndex() method => Read Here

Checking if a Javascript object contains the same key/value Lodash

Can't figure out how to find an equal key:value in the array consisted of objects.
I have an Array with the objects that look like this
[{
0:false,
1:false,
2:false,
3:true,
4:false,
5:false
},{
0:false,
1:false,
2:false,
3:true,
4:false,
5:false
},{
0:false,
1:false,
2:false,
3:true,
4:false,
5:false
}]
I need to iterate this Array with objects and if all Objects get the same key with true value (In the example above all objects have the same key:3 with value: true) and then I need to catch this key (position).
What is the best solution for this? I also use Lodash so maybe with this library it easy to get what I want or maybe to use plain javascript. It's no matter how to get it, just need a right solution.
Use _.findKey and _.every
var arr = [{"0":false,"1":false,"2":false,"3":true,"4":false,"5":false},{"0":false,"1":false,"2":false,"3":true,"4":false,"5":false},{"0":false,"1":false,"2":false,"3":true,"4":false,"5":false}];
var key = _.findKey(arr[0], function(val, key) {
return val && _.every(arr, key);
});
console.log(key);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
If you're using ES6, you can shorten that to:
let key = _.findKey(arr[0], (v, k) => v && _.every(arr, k));
If you decide to switch to a more natural 2D array structure, use _.findIndex instead.
[
[false,false,false,true,false,false],
[false,false,false,true,false,false],
[false,false,false,true,false,false],
[false,false,false,true,false,false],
[false,false,false,true,false,false]
]
First of all, I changed the objects with the keys being the index to arrays for simplicity, because that's what an array is: just a special object with indices as keys.
You can try this. It doesn't use lodash (I'm not familiar with it, sorry), but what it does is:
Start with an array of all true values that matches the length of each object (i.e., length is six)
Loop through each object and each property of each object.
If it is false, then the value of that index is false. If it is true, then the index will be true if the index is already true.
Print out the index that remains true.
You can see what I mean with the code below:
var list = [[false,false,false,true,false,false],[false,false,false,true,false,false],[false,false,false,true,false,false],[false,false,false,true,false,false],[false,false,false,true,false,false]];
var trueKeys = [true, true, true, true, true, true];
for(obj in list)
for(prop in list[obj])
trueKeys[prop] = trueKeys[prop] && list[obj][prop];
var index = trueKeys.indexOf(true);
console.log(index);

Categories

Resources