I have following array of objects data, that has multiple properties, some of them can have null value.
I want to filter through this array of objects and remove every object that has property of null value.
So far I have tried this code, but with no luck:
const noNull = data.filter((doc) => { return Object.values(doc).some(prop => { if (prop !== null) return doc; } )});
Any ideas how can I achieve this?
Thank you in advance.
Here Updated to keep items which do not have a null value
const noNull = obj.filter((doc) => { return Object.values(doc).every(prop => prop !== null)})
.some() and .every() expect boolean return value
reference
Related
In my Vue app, I am getting an array from map getters and I am trying to filter this array based on type which is a prop in a computed property. I checked both of them, both are strings, but the filter is not working properly, since I feel the computed property is called before the prop is initialized with value. Need some help with this?
all: 'mdm/all', // here 'mdm' indicates module name and 'all' is the state
prop: [type]
Inside computed, I have a property called
getData() {
const filteredData = this.all.filter(ele => ele.type === this.type.toLowerCase());
return filteredData.map(item => (
{name: item.name,
orderNo: item.order_no
});
}
In the above code, both ele.type and this.type seems to be strings with similar value (say 'expired') but the filteredData always happens to be an empty array.
Not sure what could be cause for this.
I would debug what .filter() is doing with a console log inside of it, for example:
this.all.filter(ele => {
console.log(`${ele.type} === ${this.type.toLowerCase()}?`, ele.type === this.type.toLowerCase());
return ele.type === this.type.toLowerCase();
})`
which will print out the result of ele.type === this.type.toLowerCase() every loop so you can verify what exactly is happening.
Trying to modify object value in array on condition on some arrays the override does not work, here is my snippet
const removeAction = (target, array, name) => {
let mutation = JSON.parse(JSON.stringify(array));
mutation.map( obj => {
if(obj.value === target.value) {
console.log(obj)
obj.checked = false
}
return obj
})
console.log(mutation)
removeCallback(mutation, name)
}
and I get back the original object in array. How do I debug this issue?
const modifiedArray = JSON.parse(JSON.stringify(array)).map(...
Map always returns new instance of array. So either assign that mutated map to some variable or loop over and mutate the original array.
You could take the mapped objects with destructuring the object and an updated property.
const
removeAction = (target, array, name) => {
removeCallback(array.map(obj => ({
...obj,
checked: obj.value === target.value ? false : obj.checked
})), name)
};
I have a list of array I do this:
const { id } = myArray.find(
(obj) => obj === true)
If the id is not present it will throw error. How to prevent error in the same time use destructuring? I want to keep the logic in one line.
The issue here is .find() returns undefined once there is no fulfillment for the condition:
The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
So probably you can use || operator to check if you have any value returned from .find() or you can replace with empty object {} instead on the right side of the operator.
Probably the option for one-liner is the following:
const myArray = [
{ id: 12 },
{ id: 13 },
{ id: 14 }
];
const { id } = myArray.find(e => e.id === 17) || {};
console.log(id);
So you can destructure id property even if it returned undefined in this way.
Also if you need you can add default value to your destructuring statement based on the documentation which states for Destructuring statement as follows:
A variable can be assigned a default, in the case that the value unpacked from the object is undefined.
const { id = 10 } = {};
console.log(id);
I hope this helps!
I'm recursively sorting a deeply nested array of objects by a deeply nested obj that is keyed by id.
This function works but when I console.log while invoking the function the result is undefined.
The unsorted array of objects passed as an argument does get sorted if I console.log it before and after the call to this function, but that is not being returned from the function call - it is a mutation, which I'm looking to avoid.
A couple of things I've tried:
Instead of the initial call to .map(), using .reduce(), and
adding an empty array as the accumulator, which allows the function
to return but it does not sort :/
Returning the array I'm calling .map() on at the very end works -
but this seems like a hack, and it also encloses the result in an
array.
I've tried carefully placing returns in different places - but what usually results is [undefined], or arrays of arrays that
contain undefined
function sortDeepNestedArray(unsortedArray, sortedObj){unsortedArray.map((obj) => {
const children = obj.Children;
const Id = obj.Id
if (children && children.every(o => !o.Children)) {
Object.keys(sortedObj).map(key => {
if (Id === key) {
return children.sort((a, b) => {
a = sortedObj[key].Children[a.Id]
b = sortedObj[key].Children[b.Id]
return a - b
});
}
});
}
Object.keys(sortedObj).map(key => {
const isNotBaseCase = children &&
children.every(o => o.Children) &&
Id === key &&
sortedObj[key] &&
sortedObj[key].Children
if (isNotBaseCase) {
sortDeepNestedArray(children, sortedObj[key].Children);
}
});
});
}
So I'm doing some challenges on freecodecamp, I got stuck on one that says:
"Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument)." So I looked the for the answer and came accross the next code:
function whatIsInAName(collection, source) {
var arr = [];
var keys = Object.keys(source);
// Filter array and remove the ones that do not have the keys from source.
arr = collection.filter(function(obj) {
return keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
});
return arr;
}
I understand what it does what I cant seem to get is the returns inside the collection.filter why do we need these two:
return keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
Why the code doesn't work with only the second one.
Can someone explain this to me please.
this code:
arr = collection.filter(function(obj) {
return keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
First, (this is the main script to check wheter Collection's element match or not with the source)
keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
It will just return either true/false based on obj.hasOwnProperty(key) && obj[key] === source[key]; condition. it checks every keys from source. If it finds just one key un-matched with the condition it will break the loop and return false otherwise (passed all the test [all keys and values from source the same with collection's element]) return true.
then
arr = collection.filter(function(obj) {
return true // false
if it return true, the element obj from collection will be passed to arr otherwise filtered / skipped
collection.filter is calling Array.prototype.filter. It is used for removing elements from an array that don't meet certain criteria. The function passed as a parameter is used to determine whether an element meets that criteria. A return value of false means that the element should be removed from the array, while true means that the element should stay in the array.
If you don't give the function a return statement, it will return undefined for all of the elements of the array, which is a falsy value.
In ES6, you can use arrow functions which don't require you to write return:
function whatIsInAName(collection, source) {
var keys = Object.keys(source);
return collection.filter(obj =>
keys.every(key =>
obj.hasOwnProperty(key) && obj[key] === source[key];
)
);
}