I want to find out whether an Array is present in an JavaScript object.
Dummy example:
Given a Javascript Object containing an Array. and we dont know if there is an Array present in the Object.
var dummyObject = {
backgroundcolor: '#000',
color: '#fff',
arr: ['1','2','3','4','5','6']
};
Now I want to check if there is an array in this object and if there is print all the elements of that Array.
Currently I am onto one solution i.e. to Iterate each key and check each if them if there is an array in it using Array.isArray(key).
Any help would be great.
Using Array.isArray is the correct method for going about this. Iterating through each key is pretty simple too. Then once you find the item, just log it to the console:
var dummyObject = {
backgroundcolor: '#000',
color: '#fff',
arr: ['1', '2', '3', '4', '5', '6']
};
const arr = Object.entries(dummyObject).find(([, v]) => Array.isArray(v));
if (arr) console.log(arr[1]);
.as-console-wrapper { max-height: 100% !important; top: auto; }
You can use some with Object.values if you just want a Boolean determining whether an array exists inside an object:
var dummyObject = {
backgroundcolor: '#000',
color: '#fff',
arr: ['1', '2', '3', '4', '5', '6']
};
const arrInObj = Object.values(dummyObject).some(e => Array.isArray(e));
console.log(arrInObj);
And if you want, you can avoid using Array.isArray and check for the existence of the map property instead (à la code golf):
var dummyObject = {
backgroundcolor: '#000',
color: '#fff',
arr: ['1', '2', '3', '4', '5', '6']
};
const arrInObj = Object.values(dummyObject).some(({ map }) => map);
console.log(arrInObj);
if (dummyObject.arr){
console.log('arr is present')
}else{
console.log('arr is not present')
}
Related
I am trying to make tic tac toe game in vanilla javascript. If I use ! to flip the value of object boolean property , it is changed to what it is defined in global memory object (as soon as it is out of its execution context), however If I flip by using = equal sign, it stays same. aren't they both doing same thing(flipping value)?? Any explanation would be appreciated.
Here's my code.
// we need an object for storing the state of our game.
const game = {
xTurn: true,
xState: [],
oState: [],
winningStates: [
// Rows
['0', '1', '2'],
['3', '4', '5'],
['6', '7', '8'],
// Columns
['0', '3', '6'],
['1', '4', '7'],
['2', '5', '8'],
// Diagonal
['0', '4', '8'],
['2', '4', '6']
]
}
document.addEventListener('click',e=>{
const target = e.target;
console.log('initializing code')
const isCell = target.classList.contains('grid-cell')
const isDisabled = target.classList.contains('disabled');
if(isCell && !isDisabled){
const cellValue = target.dataset.value;
if(game.xTurn){
game.xState.push(cellValue)
}else{
game.oState.push(cellValue)
}
target.classList.add('disabled')
target.classList.add(game.xTurn ? 'x' : 'o')
// if(game.xTurn){
// target.classList.add('x')
// }else{
// target.classList.add('o')
// }
console.log(game.xTurn)
game.xTurn = !game.xTurn;
// game.xTurn = false;
console.log(game.xTurn)
}
})
i have that Object with two lists inside.
const list = {
Operator: [
{
Login: 'login1',
PermissionGroup: '2',
Sub: '3',
},
{
Login: 'login2',
PermissionGroup: '3',
Sub: '2',
},
],
PermissionGroups: [
{
PermissionGroupId: '2',
GroupsName: 'Gestor',
PermissionLevel: 2,
},
{
PermissionGroupId: '3',
GroupsName: 'Lider',
PermissionLevel: 3,
},
],
};
In my redux, i have the "Sub" of the Operators. So what do I have to do...
Step 1: Get my Redux "sub" and find which Operator it is in
Step 2: Now that I have the Operator, I need to find which operator corresponds to the PermissionGroup, using the PermissioninGroup(into Operators) and the PermissionGroupId(into PermissionGroups)
This method does what I want (Ignore final return), How do I optimize this method? I didn't want to use two filters for this
const search = (sub) => {
const usuario = listaUsuarios.filter((element) => element.Sub === sub)[0];
const permissaoUsuario = listaPermissoes.filter(
(element) => element.PermissionGroupId === usuario.PermissionGroup
)[0];
return permissaoUsuario.PermissionLevel;
};
Personally, the current solution seems okay (of course, if it is confirmed that one only requires the 0-th element from .filter(), it may be preferrable to use .find() instead). Since OP has requested an alternate, the solution below (which is not my recommendation) may achieve the desired objective.
Code Snippet
const searchSub = (needle, {Operator, PermissionGroups}) => (
[...Operator, ...PermissionGroups].reduce(
(res, obj) => ({
...res,
...(
'Sub' in obj && obj.Sub === needle
? {foundSub: {...obj}}
: 'PermissionGroup' in res.foundSub &&
'PermissionGroupId' in obj &&
obj.PermissionGroupId === res.foundSub.PermissionGroup
? {matchedPermissionGroup: {...obj}}
: {}
)
}),
{foundSub: {}, matchedPermissionGroup: {}}
)
);
const list = {
'Operator': [{
'Login': 'login1',
'PermissionGroup': '2',
'Sub': '3',
},
{
'Login': 'login2',
'PermissionGroup': '3',
'Sub': '2',
}
],
'PermissionGroups': [{
'PermissionGroupId': '2',
'GroupsName': 'Gestor',
'PermissionLevel': 2,
},
{
'PermissionGroupId': '3',
'GroupsName': 'Lider',
'PermissionLevel': 3,
},
]
};
console.log(searchSub('2', list))
console.log(
'PermissionLevel: ',
searchSub('2', list)?.matchedPermissionGroup.PermissionLevel
);
Explanation
Use ... spread operator to construct one array with elements from both Operator and PermissionGroups array
Use .reduce() to iterate over this combined array
When a Sub is found, track it in res object
When a matching PermissionGroupId is found, track that as well
The resulting res object will have elements from both Operator and PermissionGroups array that matched.
NOTE
Just to reiterate, it is actually simpler to just use two separate .find() in this context.
Firstly, I am trying to merge an array of many objects into a single array with every key in each object.
Lastly, any duplicate items in the array should be removed as well as any elements named "name".
Input:
const data = [
{
name: '10/20',
Tyler: 1,
Sonia: 0,
Pedro: 0,
},
{
name: '10/23',
Tyler: 0.5,
Sonia: 0.25,
Pedro: 0.75,
George: 0.5,
},
];
Output:
["Tyler", "Sonia", "Pedro", "George"]
This is what I've tried so far:
const mergedData = data.reduce((prev, cur) => {
const obj = cur[0];
const keys = Object.keys(obj);
const names = keys.splice(1);
return { names };
}, []);
I am trying to capture any key name other than "name" and add it to the final array. However, this is where I get stuck because I get this error, TypeError: Cannot convert undefined or null to object
Note: Objects may be different lengths, contain a mix of names, but never any duplicates.
An option is to find all keys put in a set and remove the name key
const data = [
{
name: '10/20',
Tyler: 1,
Sonia: 0,
Pedro: 0,
},
{
name: '10/23',
Tyler: 0.5,
Sonia: 0.25,
Pedro: 0.75,
George: 0.5,
},
];
const set = new Set(data.reduce((acc, i) => [...acc, ...Object.keys(i)], []));
set.delete('name');
const result = [...set];
console.log(result);
If you have access to ES6 methods, you can do this using a Set (unique values are ensured at creation) and converting it back into an array if you want through Destructuring.
data = [{name: '0', Tyler: '1', Dan: '2', Carl: '3'}, {name: '0', Tyler: '1', Dan: '2', Eric: '3', Danny: '4'}];
const output = (data) => {
let output = [];
// This makes sure you get each array and then strips just the keys as desired
data.forEach(item => {
output = output.
concat(Object.keys(item))
});
// This creates the set, strips our dups, and then spreads itself into an array
return [...new Set(output)]
// Strip out the 'name' key as needed
// NOTE: This should be a param instead of hard-coded, but this is easier to show
.filter(res => res != 'name');
}
console.log(output(data));
This should be fairly performant considering it only navigates the full array one time and each object itself shouldn't have millions of properties to cause .keys() any issues.
I have an array of objects that I would like to know how to parse, find the keys that are in my other array and check if they are null in the initial array of objects.
How can I achieve this?
So I have something like:
[{"nonmandatoryfield":"","mandatoryfield1":"1","mandatoryfield2":"2",
"mandatoryfield3":"3"}]
now I would like to check if keys: [mandatoryfield1, mandatoryfield2, mandatoryfield3] values are null
In JavaScript
Maybe you want something like this:
const mandatoryFieldNames = [
'mandatoryfield1',
'mandatoryfield2',
'mandatoryfield3',
];
const data = [
{
nonmandatoryfield: '',
mandatoryfield1: '1',
mandatoryfield2: '2',
mandatoryfield3: '3',
},
{
nonmandatoryfield: '',
mandatoryfield1: null,
mandatoryfield2: '2',
mandatoryfield3: '3',
},
];
const dataWithMandatoryFields = data.filter(item =>
mandatoryFieldNames.every(field => item[field]),
);
How to log in console the items of this array if they have index like 0, 1, 2 ?
products: Array(1)
0:
name: 'abc',
size: 'S',
color: 'white'
1:
name: 'abc',
size: 'S',
color: 'white
how i access to items:
products.forEach(product=> {
console.log(product.name);
});
when i console.log in forEach i get two product item names too. Everything is okey with this.
but when i console.log outside of forEach i can't get the name of two properties but i need to set this names to another object like
sendProducts = {
productName = products.name
}
As shown it is looking like a Array of Objects
Your Object is
object : {
name: 'abc',
size: 'S',
color: 'white
}
And Array is something like this
products: Array(1)
0:
name: 'abc',
size: 'S',
color: 'white'
1:
name: 'abc',
size: 'S',
color: 'white
Lets First understand how we created this Array of object
var products = [];
var object1= {name:"abc",size:"S",color:"white"};
products.push(object1);
var object2= {name:"xyz",size:"M",color:"black"};
products.push(object2);
//Now About your actual Question how to access the values of objects
console.log(products[0].name);
console.log(products[0].size);
console.log(products[0].color);
console.log(products[1].name);
console.log(products[1].size);
console.log(products[1].color);
// or you can loop in here
var productName = []
for(let i=0;i<products.length;i++){
productName.push(products[i].name);
}
console.log("Product Names Array "+productName);
Hope this Explaination Helps
how about console.log(products.map(p -> p.name)
If you want to log the name of one specific item, you can use:
console.log(products[0].name)
If you want to log the name of all items, use the forEach function:
products.forEach(product => {console.log(product.name)})