Check all object values inside Array javascript has boolean false - javascript

I have below object inside array
[
{
"age":32,
"test":true
},
{
"age":33,
"test":true
},
{
"age":35,
"test":false
}
]
I need to check if all values of test is false.
I have tried below code
Array.isArray(obj.map((message,index) => {
if(message.test !== message.test){
//trigger when all values are false
}
}))
How to achieve this?

You can use every from Array prototype:
let areAllFalse = array.every(x => x.test === false);

You can also you filter from array prototype...
const filtered = array.filter(a => a.test === true)
or the less verbose
const filtered = array.filter(a => a.test)

Related

new Array Conditional values

I need to create a new array as you can see it has a key value that specifies the latitude and longitude.
I want the key values ​​that are equal to be set as 1 only but according to who has the highest count
[
{
"color":"green",
"coment_calification":"Califica",
"count":7,
"key":"-13.0711552&-76.3723776&Califica",
"latitud":"-13.0711552",
"longitud":"-76.3723776"
},
{
"color":"yellow",
"coment_calification":"Reporte",
"count":6,
"key":"-13.0711552&-76.3723776&Reporte",
"latitud":"-13.0711552",
"longitud":"-76.3723776"
},
{
"color":"green",
"coment_calification":"Califica",
"count":1,
"key":"-13.1711552&-76.3423776&Califica",
"latitud":"-13.1711552",
"longitud":"-76.3423776"
},
{
"color":"yellow",
"coment_calification":"Reporte",
"count":2,
"key":"-13.1711552&-76.3423776&Reporte",
"latitud":"-13.1711552",
"longitud":"-76.3423776"
}
]
let result = count.filter((e) => e && e.count && e.key == e.key);
let datas = result;
Is this what you're looking for?
const result = arr.reduce((acc, cur) => {
const matchIndex = acc.findIndex(saved =>
saved.latitud === cur.latitud
&& saved.longitud === cur.longitud
);
if (matchIndex !== -1) {
if (cur.count > acc[matchIndex].count) {
acc.splice(matchIndex, 1, cur);
}
return acc;
}
return [...acc, cur];
}, []);
It looks like the array contains objects that differ mostly by their count props but have several other duplicate props. I think I understand the OP to want to remove these almost-duplicates retaining the one with the highest count.
One way to do this is to sort the array to be descending by count, walk through them, pushing onto a result only those that aren't already in the result.
The only thing not super clear in the OP is what constitutes sameness besides the count field. Here, we guess that the coment_calification key being the same means the objects are to be treated as duplicate.
const objects = [
{
"color":"green",
"coment_calification":"Califica",
"count":7,
"key":"-13.0711552&-76.3723776&Califica",
"latitud":"-13.0711552",
"longitud":"-76.3723776"
},
{
"color":"yellow",
"coment_calification":"Reporte",
"count":6,
"key":"-13.0711552&-76.3723776&Reporte",
"latitud":"-13.0711552",
"longitud":"-76.3723776"
},
{
"color":"green",
"coment_calification":"Califica",
"count":1,
"key":"-13.1711552&-76.3423776&Califica",
"latitud":"-13.1711552",
"longitud":"-76.3423776"
},
{
"color":"yellow",
"coment_calification":"Reporte",
"count":2,
"key":"-13.1711552&-76.3423776&Reporte",
"latitud":"-13.1711552",
"longitud":"-76.3423776"
}
];
objects.sort((a,b) => b.count-a.count) // sort descending
const result = [];
for (let object of objects) {
// supposing matching coment_calification props means a match
let alreadyInResult = result.find(r => r.coment_calification === object.coment_calification)
if (!alreadyInResult) result.push(object);
}
console.log(result)

How to insert key in object based on Id

I have an array of object, I want to add key in my specifi object of array when Id is matched. I have tried this:
this.data.forEach(value => {
if (value.Id === attachmentDataId) {
AttachmentTypeId: this.attachmentRecord.AttachmentType;
}
});
But it's not working and it's not giving any error also
Try this out :
let data = [{ id: 1 }, { id: 5 }];
const attachmentDataId = 5;
const attachmentRecord = { AttachmentType: "AttachmentType" };
data.forEach(value => {
if (value.id === attachmentDataId) {
value.AttachmentTypeId = attachmentRecord.AttachmentType;
}
});
The stackblitz example: https://stackblitz.com/edit/js-nrhouh
You could use the index parameter of forEach function to access the specific object of the array.
this.data.forEach((value, i) => {
if (value.Id === attachmentDataId) {
this.data[i] = {
...this.data[i],
AttachmentTypeId: this.attachmentRecord.AttachmentType
};
}
});
Inside the if block, you could also instead do
this.data[i]['AttachmentTypeId'] = this.attachmentRecord.AttachmentType;
I just find using the spread operator cleaner.
use javascript map() method.
Map() return a new array, it takes a callback, iterates on each element in that array
const updatedData = data.map(res => {
if(res.id === attachmentDataId) {
res.AttachmentTypeId = attachmentRecord.AttachmentType;
}
return res
})

How to change property values in an array Object?

I'm trying to change the values of each property in an array using a forEach function but not having any luck.
Here's my array:
this.panels = [
{ isRandomPanel : false },
{ isMyPanel : false },
{ isFavorite : false },
{ isEatable : false }
]
I'm trying to update the value of each property to true so finally I can get this:
isRandomPanel = true
isMyPanel = true
isFavorite = true
isEatable = true
I'm trying to use the forEach function but I'm stuck:
this.panels.forEach(panel => panel.isRandomPanel = true);
Does anyone know how to make this happen using pure Javascript, TypeScript or ES6?
If those are the only keys on the objects, you can iterate over Object.keys(panel) and set each panel[key] = true, like so:
var panels = [
{ isRandomPanel : false },
{ isMyPanel : false },
{ isFavorite : false },
{ isEatable : false }
];
// set all panel flags to true
panels.forEach(function (panel) {
Object.keys(panel).forEach(function (key) {
panel[key] = true;
});
});
console.log(panels);
Or, with shortened ES6 Syntax:
panels.forEach(panel => Object.keys(panel).forEach(key => panel[key] = true));
You need to itreate over the array, get each key from the object and set the value of that key to true. You can use Object.keys or for in loop to get the keys:
this.panels.forEach(panel => {
for(const key of Object.keys(panel))
panel[key] = true
})
OR
this.panels.forEach(panel => {
for(const key in panel)
panel[key] = true
})
As you are using ES 6, So following will work
panels.forEach(panel => Object.keys(panel).forEach(key => panel[key] = true));

Object push Firebase, how to remove key names from pushed items

I have this Object.key code that pushes all items:
const cloned_items = [];
Object.keys(items).sort().map(key => {
let item = {
[`item-${uid}`]: {
item: false
}
}
cloned_items.push({ ...item });
});
database.ref('/app/items').update({
...cloned_items
})
but this produces following result:
"0" : {
"timeslot-87dah2j" : {
item: false
}
},
"1" : {
"timeslot-7s1ahju" : {
item: false
}
}
instead of:
"timeslot-87dah2j" : {
item: false
},
"timeslot-7s1ahju" : {
item: false
}
any idea ?
It seems like you want to create a plain object, not an array.
In that case:
const cloned_items = Object.assign(...Object.keys(items).map(uid =>
({ [`item-${uid}`]: {item: false} })
));
NB: sorting is of no use when creating an object -- its keys are supposed to have no specific order.
You're creating an array of objects. Seems like you want to use .reduce() to create a single object from the array.
const cloned_items = Object.keys(items).sort().reduce((obj, key) =>
Object.assign(obj, { [`item-${uid}`]: { item: false } })
, {});
Your code doesn't show where uid is coming from, but I assume you meant key there, along with timeslot instead of item.
You may find Object.defineProperty to be cleaner, though you'll need to set up the property descriptor as you want it.
const cloned_items = Object.keys(items).sort().reduce((obj, key) =>
Object.defineProperty(obj, `item-${uid}`, {value:{item: false}})
, {});

Simpler method of filtering array of object of array of objects

I'm trying to filter an array of objects which has objects of array of objects inside. For example, an object in an array would look like this.
list=[...,
{
"types": [
{
"slot": 2,
"type":
{
"url": "http://pokeapi.co/api/v2/type/4/",
"name": "poison"
}
},
{
"slot": 1,
"type":
{
"url": "http://pokeapi.co/api/v2/type/12/",
"name": "grass"
}
}
],
"name": 'bulbasaur'
},...
]
I'm currently filtering the list by its name and the types of objects like this (the this.props.search.search being a string, and the example being an example list of strings that will be adjusted):
let filtered = this.props.pokemons.filter((pokemon)=>{
return pokemon.name.toLowerCase().indexOf(this.props.search.search.toLocaleLowerCase())!==-1;
})
let example = ['fire', 'ice', 'water'];
let filteredx= filtered.filter((pokemon)=>{
return pokemon.types.filter((type)=>{
return example.indexOf(type.type.name)!==-1
}).length>0
})
Is there a method of combining all the filters into one instead of calling
array.filter(...).filter(...)
As in the future, if more filters are added, I'm afraid that it's going to end up looking like
array.filter(...).filter(...).filter(...).filter(...).filter(...)
Any help would be appreciated.
You can combine the two conditions with an &&:
let filteredx = this.props.pokemons.filter(pokemon =>
pokemon.name.toLowerCase().includes(this.props.search.search.toLocaleLowerCase())
&& pokemon.types.some(type => example.includes(type.type.name))
)
Note you can use includes and some in your conditions, and use the expression syntax in your arrow functions (without braces nor return).
You can add more conditions with additional && operators. Make sure to put them in such order that the most simple conditions (that require least work) come first.
If the array is small and perfomance not an issue;
const arryOfPokemons = [{name: 'name1', type: 'type1'}];
function name(pokemon) { return pokemon.name !== 'name' }
function type(pokemon) { return pokemon.type !== 'type' }
const result = [name, type].reduce((result, filterFunc) => result.filter(filterFunc), arryOfPokemons);
otherwise you can try to combine the conditions into the same filter function.
Instead of filtering multiple times, you can combine all the filter conditions in one filter.
Instead of doing this...
let filtered1 = toFilter.filter((element) => {
return condition1;
});
let filtered2 = filtered1.filter((element) => {
return condition2;
});
...
let filteredN = filteredN_1.filter((element) => {
return conditionN;
});
... you can combine the conditions in a single filter:
let filtered = toFilter.filter((element) => {
return condition1 && condition2 && ... && conditionN;
});
If one of the conditions is very long, you can easily abstract it in a separate function. This also makes the code more readable and maintainable.
let filtered = toFilter.filter((element) => {
const condition1 = computeCondition1(arg1, arg2);
const condition2 = computeCondition2(arg1);
...
const condition3 = computeCondition3(arg2, arg3, arg4);
return condition1 && condition2 && ... && conditionN;
});
You could define an object which contains a property for every first level property of your pokemon list you want to test. The value would be a predicate with the "test logic" for this property.
const pokemons = [
{"name":"poke1","types":[{"type":{"name":"poison"}},{"type":{"name":"grass"}}]},
{"name":"poke2","types":[{"type":{"name":"fire"}},{"type":{"name":"grass"}}]},
{"name":"poke3","types":[{"type":{"name":"ice"}},{"type":{"name":"water"}}]},
{"name":"poke4","types":[{"type":{"name":"ice"}},{"type":{"name":"grass"}}]}
];
const filterOptions = {
name: (name) => {
return ["poke1", "poke5"].some(x => x === name);
},
types: (types) => {
return ["ice", "water"].some(t => types.some(x => t === x.type.name));
}
};
function filterList(list, options) {
return list.filter(pokemon => {
return Object.keys(options)
.some(key => {
if (key in pokemon) {
return filterOptions[key](pokemon[key]);
}
});
});
}
const filtered = filterList(pokemons, filterOptions);
filtered.forEach(p => console.log(JSON.stringify(p)));

Categories