Get Keys With Value From Inside Object - javascript

I have an object like this:
trueOptions = {
trueOption1 : true,
trueOption2 : true,
trueOption3 : false,
trueOption4 : false,
trueOption5 : true
}
I want to get the keys for the items with true values from inside the object.
How can I get these items?
Thanks.

You can use filter and map on Object.entries
const options = {
trueOption1: true,
trueOption2: true,
trueOption3: false,
trueOption4: false,
trueOption5: true
}
const trueOptions = Object.entries(options).filter(option=>option[1]).map(option=>option[0])
console.log(trueOptions)

You can use Object.keys() to iterate through each key and then use array#filter to filter out keys whose value is true.
const trueOptions = { trueOption1 : true, trueOption2 : true, trueOption3 : false, trueOption4 : false, trueOption5 : true },
result = Object.keys(trueOptions).filter(k => trueOptions[k]);
console.log(result);

Option 1
See Object.entries(), Array.prototype.filter(), and Array.prototype.map() for more info.
// Input.
const options = {option1: true,option2: true,option3: false,option4: false,option5: true}
// Trues.
const trues = obj => Object.entries(obj).filter(([key, value]) => value).map(([key]) => key)
// Output.
const output = trues(options)
// Proof.
console.log(output)
Option 2
See Object.keys() and JSON for more info.
// Input.
const options = {option1: true,option2: true,option3: false,option4: false,option5: true}
// Trues.
const trues = obj => Object.keys(JSON.parse(JSON.stringify(obj, (k, v) => v || undefined)))
// Output.
const output = trues(options)
// Proof.
console.log(output)

Object.keys(trueOptions).forEach(d=>{if(trueOptions[d] != true){delete trueOptions[d];}})
Object.keys(trueOptions)

Related

Check for a key inside In array of objects

I am trying to find the best way to check whether an object key is present inside multiple objects present in an array which will provide a boolean as output
[{alert:hi},{alert:bye},{}]
From the above example basically what I am trying to achieve is if any one object is missing the alert object key the output should be as false or anything
You can iterate your array with every(). Something like this:
const objects = [{alert:'hi'},{alert:'bye'},{}];
const every = objects.every(obj => obj.hasOwnProperty('alert'));
console.log(every);
You can use the Array#some method and check if at least one element is undefined
const isAlertMissing = (array) => array.some(elem => elem.alert === undefined)
const objs1 = [{alert: "foo"},{alert: "foo"},{}]
const objs2 = [{alert: "foo"},{alert: "foo"}]
console.log(isAlertMissing(objs1))
console.log(isAlertMissing(objs2))
You can use every to check all items and some with Object.keys for finding a key in the inner objects.
const data = [{alert:"hi"},{alert:"bye"},{}]
const result = data.every(item => Object.keys(item).some(key => key === "alert"));
console.log(result) //false
EDIT
some with Object.keys is kind of roundabout, so we can use hasOwnProperty instead.
const data = [{alert:"hi"},{alert:"bye"},{}]
const result = data.every(item => item.hasOwnProperty("alert"));
console.log(result) //false
Array#some will succeed as soon a match is found, making it more efficient than Array#every.
const test = (data, propName) =>
!(data.some((el) => !el.hasOwnProperty(propName)))
const data1 = [ {alert:'hi'}, {alert:'bye'}, {}]
const data2 = [ {alert:'hi'}, {alert:'bye'}]
console.log(test(data1, 'alert')) // false
console.log(test(data2, 'alert')) // true
Or:
const test = (data, propName) => {
for(let el of data) {
if(!el.hasOwnProperty(propName))
return false
}
return true
}
const data1 = [ {alert:'hi'}, {alert:'bye'}, {}]
const data2 = [ {alert:'hi'}, {alert:'bye'}]
console.log(test(data1, 'alert')) // false
console.log(test(data2, 'alert')) // true

Adding elements in the array on the basis of an object

const prefer={"cs":{"c1":true,"c2":true,"c3":false,"c4":true}}
setArray((prevArray)=>{
return prevArray.filter(function(array){
//code here
})
});
I want to set array on the basis of prefer object, like if c1 is true then is want to add it in the array
Do I need to initialize the array too?
In above example array=["c1","c2","c4"] .
Also do we need filter method or can we use some other method
You can use for-in loop to iterate map/object
const prefer = { c1: true, c2: true, c3: false, c4: true };
let arr = [];
for (let key in prefer) {
if (prefer[key]) arr.push(key); // modify how u want to save
// arr.push({ [key]: prefer[key] }); // if u want key and value
}
console.log(arr);
You can express it as follows,
const prefer = { "c1":true, "c2":true, "c3":false, "c4":true }
const output = Object.entries(prefer)
.filter(([, value]) => value) // !!value or Boolean(value) to coerce
.map(([key]) => key)
console.log(output)
This is sort of convoluted, but it works:
const prefer = {
"c1": true,
"c2": true,
"c3": false,
"c4": true
}
var setArray = ( prevArray ) => {
return Object.keys(prevArray).filter(function(val, i) {
if ( prevArray[Object.keys(prevArray)[i]] ) return Object.keys(prevArray)[i];
})
};
console.log( setArray(prefer) );

JS - Get object key-value pairs for filtered values WITHOUT underscore

I have a problem with filtering object's values by true/false, just like in this topic Get object keys for filtered values but without underscore, meaning using exclusively plain JS. There are many more or less similar questions on StackOverflow, but unfortunately I failed to set a working approach.
For example, I have an object:
var anObject = {first_property: false, second_property: true, third_property: false, fourth_property: false, fifth_property: false, sixth_property: true, seventh_property: false, eight_property: nine-nth_property: false}
I need to get a new object, featuring exclusively truthy values, like:
var newObject = { second_property: true, sixth_property: true }
To filter, I wrote the following filter:
function isValid(value) {
if (typeof value === "undefined" || value == null || value.length == 0 || value == false) {
return false;
} else {
return true;
}
}
Broke my head and spent a few hours trying different approach, however the result is unsatisfactory. How should I built the algorithm to do this, which custom/out-of-the-box functions is worth using here? Thanks in advance!
You need to loop over the key/value pairs and find out which are true. The solution works as follows:
Gets the key/value pairs from the object using Object.entries.
Iterates over the entries using Array.reduce.
In each iteration, checks if value is true. If so, then adds the key/value pair to the result.
var obj = {
first_property: false,
second_property: true,
third_property: false,
fourth_property: false,
fifth_property: false,
sixth_property: true,
seventh_property: false
};
var res = Object.entries(obj)
.reduce((result, [key, value]) => {
if (value) {
result[key] = value;
}
return result;
}, {})
console.log(res);
There are a few ways to do this using Object.entries() or Object.keys(), different array methods, etc, but I figured I'd provide one. Filter the keys down to those where the value is true, and then add those keys to the output.
var obj = {
first_property: false,
second_property: true,
third_property: false,
fourth_property: false,
fifth_property: false,
sixth_property: true,
seventh_property: false
};
var output = {};
Object.keys(obj) //Get all keys from the object ['first_property', 'second_property', ...]
.filter((key) => obj[key]) //Filter the list of keys down to only those where their value is true
.forEach((key) => output[key] = obj[key]); //For each key in our filtered list, add it to the output object
console.log(output);
Also it is possible by reducing Object.keys array (without additional filtering):
Object.keys(obj).reduce((acc, key) =>
((obj[key] ? acc[key] = obj[key] : null), acc)
, {});
// {second_property: true, sixth_property: true}
And a bit shorter version:
Object.keys(obj).reduce((acc, key) => (obj[key] && (acc[key] = obj[key]), acc), {});
You can filter (Array.prototype.filter) the truthy keys and create a new object (Array.prototype.reduce) with those:
var obj = {first_property: false,second_property: true,third_property: false,fourth_property: false,fifth_property: false,sixth_property: true,seventh_property: false};
var result = Object.keys(obj).filter(k => obj[k]).reduce((a,k) => (a[k] = obj[k], a), {});
console.log(result);

Adding keys to a json using an array of string

I have a basic json question that is giving me headache since a couple of hours, I am trying to dynamically add keys to a Json object using an array of string.
Here is my array of string:
let key = ['session', 'view_state', 'footer', 'config', 'items']
I have another variable which is jsonValue and is my whole json object. I want to end up with one of those options:
jsonValue.session.view_state.footer.config.items
jsonValue['session']['view_state']['footer']['config']['items']
This is my best attempt using a forEach.
forEach(jsonKeys, (el) => {
jsonCollection += jsonCollection !== undefined ? '."' +[el + '"'] : [ '"' + el + '"' ];
})
But I have this result: 
undefined"session"."view_state"."footer"."config"."items"
Any help will be appreciated!
To get a value using the keys array
Iterate with Array#reduce, check the type of the current value, if it's an object, return the value of the key, if not return undefined:
const obj = {
"demo": true,
"session": {
"view_state": {
"footer": {
"config": {
"items": [
1,
2
]
}
}
}
}
};
const keys = ['session', 'view_state', 'footer', 'config', 'items'];
const value = keys.reduce((val, key) => val && typeof val === 'object' ?
val[key] : undefind, obj);
console.log(value);
To add a value using the keys array
Use Array#reduceRight to create a chain of objects with the value you want. Use Object#assign to update the original object with the results:
const keys = ['session', 'view_state', 'footer', 'config', 'items'];
const obj = { demo: true };
Object.assign(obj, keys.reduceRight((val, key) => ({ [key]: val }), [1, 2])); // replace [1, 2] with the actual items
console.log(obj);

how to check if all object keys has false values

JS Object:
var saver = {
title: false,
preview: false,
body: false,
bottom: false,
locale: false
};
The question is how to check if all values is false?
I can use $.each() jQuery function and some flag variable, but there may be a better solution?
Updated version. Thanks #BOB for pointing out that you can use values directly:
Object.values(obj).every((v) => v === false)
Also, the question asked for comparison to false and most answers below return true if the object values are falsy (eg. 0, undefined, null, false), not only if they are strictly false.
This is a very simple solution that requires JavaScript 1.8.5.
Object.keys(obj).every((k) => !obj[k])
Examples:
obj = {'a': true, 'b': true}
Object.keys(obj).every((k) => !obj[k]) // returns false
obj = {'a': false, 'b': true}
Object.keys(obj).every((k) => !obj[k]) // returns false
obj = {'a': false, 'b': false}
Object.keys(obj).every((k) => !obj[k]) // returns true
Alternatively you could write
Object.keys(obj).every((k) => obj[k] == false)
Object.keys(obj).every((k) => obj[k] === false) // or this
Object.keys(obj).every((k) => obj[k]) // or this to return true if all values are true
See the Mozilla Developer Network Object.keys()'s reference for further information.
This will do the trick...
var result = true;
for (var i in saver) {
if (saver[i] === true) {
result = false;
break;
}
}
You can iterate objects using a loop, either by index or key (as above).
If you're after tidy code, and not repeating that then simply put it in a function...
Object.prototype.allFalse = function() {
for (var i in this) {
if (this[i] === true) return false;
}
return true;
}
Then you can call it whenever you need, like this...
alert(saver.allFalse());
Here's a working sample...
Object.prototype.allFalse = function() {
for (var i in this) {
if (this[i] === true) return false;
}
return true;
}
var saver = {
title: false,
preview: false,
body: false,
bottom: false,
locale: false
};
console.log("all are false - should alert 'true'");
console.log(saver.allFalse());
saver.body = true;
console.log("one is now true - should alert 'false'");
console.log(saver.allFalse());
In a comment you ask if you can avoid iteration. You can if you use a javascript library supporting a functional approach, like Underscore, Lodash or Sugar.
With Underscore and Lodash you can write something like this:
var result = _.every(_.values(saver), function(v) {return !v;});
With Sugar you can simply write:
var result = Object.all(saver,false);
Use array.some()
It's more clean and understandable! And it can save us running time, because once the function condition exist once, it goes out of the loop and returns true.
Object.values(obj).some(val => val)
if you actually need strict equality to false write this:
Object.values(obj).some(val => val !== false)
Object.values(obj) make an array with the values of each key.
Short and handy one-liner, fully supported by browsers:
Object.keys(saver).every(k => saver[k] === false);
or
Object.values(saver).every(v => v === false);
(careful tho, Object.values() is not supported by IE yet.)
This should work on all major browsers:
Object.keys(saver).every(key => saver[key] === false); // return true
Do like this,
for (var i in saver) {
if (saver[i]) {
return false; // here if any value is true it wll return as false /
}
}
return true; //here if all value is false it wll return as true
If you want to do it without external iteration (i.e. in your code), try mapping the properties to an array with $.map then using $.inArray to see if any true values exist:
var allFalse = $.inArray(true, $.map(saver, function(obj){return obj})) < 0;
JSFiddle: http://jsfiddle.net/TrueBlueAussie/FLhZL/1/
With lodash you could also do const allFalse = !_.some(saver);
Lodash (3.10.1+) makes this even cleaner to express explicitly:
_.every({a: false, b: false, c: false}, _.negate(Boolean)); // True
But using _.some per ngstschr's answer is more succinct.
✏️ This one-liner checks if there's a falsy value inside any object of an array of objects:
const hasFalsyValue = (list) =>
!list.every(obj => Object.values(obj).every(prop => prop))
I find this one useful to prevent null / falsy values from being passed further on:
const listA = [ { a:'🍎', b:100 }, { a:'🍌', b:200 } ]
const listB = [ { a:null, b:100 }, { a:'🍌', b:200 } ]
// hasFalsyValue(listA) === false
// hasFalsyValue(listB) === true
There's just one detail we should be aware of:
⚠️ In Javascript 0 and '' are Falsy values! ⚠️
So if hasFalsyValue() finds any zero value or any empty string value inside an object in the array, it will consider it a falsy value and thus return true!
...While this might be what you want, sometimes you might want to allow any particular Falsy value to be considered as Truthy.
✍🏽 Say you want to allow zero values in your objects, you can do the following:
const hasFalsyValue_ZeroAllowed =
(list) => !list.every(obj => Object.values(obj).every(prop => prop || prop === 0))
Now zero values won't be considered falsy anymore:
const listC = [ { a:0, b:100 }, { a:'🍌', b:200 } ]
const listD = [ { a: null, b:100 }, { a:'🍌', b:200 } ]
hasFalsyValue_ZeroAllowed(listC) // false
hasFalsyValue_ZeroAllowed(listD) // true
And you can keep on adding further conditions to the function for a tailored validation:
✍🏽 To allow null values:
const hasFalsyValue_NullAllowed =
(list) => !list.every(obj => Object.values(obj).every(prop => prop || prop === null))
const listE = [ { a: null, b:100 }, { a:'🍌', b:200 } ]
hasFalsyValue_NullAllowed(listE) // false
✍🏽 To allow empty string values:
const hasFalsyValue_EmptyStringAllowed =
(list) => !list.every(obj => Object.values(obj).every(prop => prop || prop === ''))
const listF = [ { a: '', b:100 }, { a:'🍌', b:200 } ]
hasFalsyValue_EmptyStringAllowed(listF) // false
As of Lodash 4.0, overEvery can be used
overEvery(saver, false) loops through every element & checks if its false
It returns true if every element is false otherwise returns false

Categories

Resources