Filter object properties by key in ES6
If you have a list of allowed values, you can easily retain them in an object using:
const raw = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' }};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw) .filter(key => allowed.includes(key)) .reduce((obj, key) => { obj[key] = raw[key]; return obj; }, {});
console.log(filtered);
How to filter an object with its values in ES6
You can use reduce()
to create new object and includes()
to check if value of object exists in array.
const acceptedValues = ["value1", "value3"]const myObject = { prop1: "value1", prop2: "value2", prop3: "value3"}
var filteredObject = Object.keys(myObject).reduce(function(r, e) { if (acceptedValues.includes(myObject[e])) r[e] = myObject[e] return r;}, {})
console.log(filteredObject)
How to filter object array based on attributes?
You can use the Array.prototype.filter
method:
var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});
Live Example:
var obj = { 'homes': [{ "home_id": "1", "price": "925", "sqft": "1100", "num_of_beds": "2", "num_of_baths": "2.0", }, { "home_id": "2", "price": "1425", "sqft": "1900", "num_of_beds": "4", "num_of_baths": "2.5", }, // ... (more homes) ... ]};// (Note that because `price` and such are given as strings in your object,// the below relies on the fact that <= and >= with a string and number// will coerce the string to a number before comparing.)var newArray = obj.homes.filter(function (el) { return el.price <= 1000 && el.sqft >= 500 && el.num_of_beds >= 2 && el.num_of_baths >= 1.5; // Changed this so a home would match});console.log(newArray);
JavaScript: filter() for Objects
Never ever extend Object.prototype
.
Horrible things will happen to your code. Things will break. You're extending all object types, including object literals.
Here's a quick example you can try:
// Extend Object.prototype
Object.prototype.extended = "I'm everywhere!";
// See the result
alert( {}.extended ); // "I'm everywhere!"
alert( [].extended ); // "I'm everywhere!"
alert( new Date().extended ); // "I'm everywhere!"
alert( 3..extended ); // "I'm everywhere!"
alert( true.extended ); // "I'm everywhere!"
alert( "here?".extended ); // "I'm everywhere!"
Instead create a function that you pass the object.
Object.filter = function( obj, predicate) {
let result = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key) && !predicate(obj[key])) {
result[key] = obj[key];
}
}
return result;
};
Cannot get properties of an object after using filter()
It's strange this doesn't work...
You can try find
. It will return the object you looking for:
{Object.values(articles).find(a => a.id==36).title || 'fallback if article is not found'}
Java Script filter nested object properties by value
Since you want to keep the object structure, you should use Object.entries
instead of Object.values
and to revert back to object type use Object.fromEntries
:
Object.fromEntries(Object.entries(input).filter(...))
To make it work for multiple keys, use every
in combination with includes
as predicate:
keys.every(key => tags.includes(key))
const input1 = {
"0":{
"id":"01",
"name":"item_01",
"tags":["a","b"],
},
"1":{
"id":"02",
"name":"item_02",
"tags":["a","c","d"],
},
"2":{
"id":"03",
"name":"item_03",
"tags":["a","b","f"],
}
}
function search(input, keys) {
return Object.fromEntries(
Object.entries(input).filter(([, { tags }]) => keys.every(key => tags.includes(key)))
)
}
console.log(search(input1, ["a", "b"]));
Filter object properties by key, but keep filtered keys from whitelist as empty
Since you need all of your allowed keys in your filtered
object, you can loop over the allowed
array and check if the whitelist key
is present in your raw object
and simply add the key if not present with null
or desired value. Sample code is below.
const raw = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' },};
const allowed = ['item1', 'item3'];
let filtered = {}
allowed.forEach( key => { filtered[key] = (typeof raw[key] === 'undefined') ? '' : raw[key];})
console.log(filtered);
JS ES6 Correct way to filter object by array of keys
You could map the wnated entries and builds objects with it.
const keys = ['key_1', 'key_3'], data = [{ key_1: 'Some Value A', key_2: 'Some Other Value A', key_3: 'Some Final Value A' }, { key_1: 'Some Value B', key_2: 'Some Other Value B', key_3: 'Some Final Value B' }, { key_1: 'Some Value C', key_2: 'Some Other Value C', key_3: 'Some Final Value C' }], result = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
Underscore Template Throwing Variable Not Defined Error
What's Wrong with Awaiting a Promise Chain
How to Open a Bootstrap Modal Window Using Jquery
Constructor Function VS Factory Functions
How to Redirect with JavaScript
Differencebetween 'New Object()' and Object Literal Notation
Execute the Setinterval Function Without Delay the First Time
Jquery .Ready in a Dynamically Inserted Iframe
Call an Asynchronous JavaScript Function Synchronously
How to Prevent Enter Keypress to Submit a Web Form
Is JavaScript Supported in an Email Message
How to Fix Error: Listen Eaddrinuse While Using Nodejs
Javascript: Filter() for Objects
Does IE9 Support Console.Log, and Is It a Real Function
How to Access Svg Elements with JavaScript
React Native - Image Require Module Using Dynamic Names