Check if value exists in object - javascript

I have object:
var roles = { roles: [0: { name: 'admin' }, 1: { name: 'user' }] }
How I can check if value user exists?
I tried do:
console.log(('user' in roles));
But this return false. Why?

With a proper object, you could treat roles.roles as array and find the value with Array#some.
This works for any array like structure with an assignment to an array with Object.assign.
function check(name) {
return Object.assign([], roles.roles).some(o => o.name === name);
}
var roles = { roles: { 0: { name: 'admin' }, 1: { name: 'user' } } };
console.log(check('user'));
console.log(check('bar'));
By taking an array directly, you coult omit the assignment part.
function check(name) {
return roles.roles.some(o => o.name === name);
}
var roles = { roles: [{ name: 'admin' }, { name: 'user' }] };
console.log(check('user'));
console.log(check('bar'));

in operator checks for property not for it's values
let test = {'a':1,'b':2}
console.log('a' in test)
console.log(1 in test)
How can i search values
Here using some method of array i am checking whether desired value is in object or not.
var roles = { roles: [{ name: 'admin' },{ name: 'user' }] }
let searchValue = (input,searchKey) => {
return input.some(( {name} ) => name === searchKey) //
}
console.log(searchValue(roles.roles, 'user'))
console.log(searchValue(roles.roles, 'user not foound'))

Related

Assign value of object and nested object in JavaScript

So, basically, I have this object (in vue data()):
...
detail: {
title: 'I have no idea',
date: 2020-02-12,
sender: {
name: 'John Cenna',
username: 'john10'
},
receipent: {
name: 'Katleen',
username: 'katmeow'
},
....
}
Now, I want to assign all of them to be null (for validation process, kind of) but couldn't assign the nested object (the object without child is fine with just loop). How do I do this? thank you
A recursive solution:
Use Object.entries() to iterate the key-value entries of the object as follows. Note that Object.entries() returns an empty array for non-objects.
If the entry's value is already null or undefined, return.
If the entry's value is an array, recurse on each array item (go to step 1 with the array item as the new object to evaluate).
If the entry's value is an object, recurse on the object.
Otherwise, set the entry's value to null.
const data = {
detail: {
title: 'I have no idea',
date: 2020 - 02 - 12,
sender: {
name: 'John Cenna',
username: 'john10'
},
receipent: {
name: 'Katleen',
username: 'katmeow'
},
items: [
{ id: 100, name: 'Apple' },
{ id: 200, name: 'Banana' },
{ id: 300, name: 'Orange' },
]
}
}
function nullify(obj) {
// 1
Object.entries(obj).forEach(([k,v]) => {
// 2
if (v === null || v === undefined) {
return
}
// 3
if (Array.isArray(v)) {
return v.forEach(nullify)
}
// 4
if (typeof v === 'object') {
nullify(obj[k])
} else {
// 5
obj[k] = null
}
})
}
nullify(data.detail)
console.log('res', data.detail)

How to access an array of objects which is a key-value pair

i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])

How to get unique values from object array

I have a mapped an array object, now I need to get unique values from that array's children.
const arr=[
{
name: 'name1',
functions:{
0:{
name:'some1',
property: 'string'
},
1:{
name:'some1',
property: 'string'
},
2:{
name:'some3',
property: 'number'
}
}
},
]
<div>
{
arr.map((item, index) => {
let ars=[]
//console.log(item.functions)
for(const key in item.functions){
if(ars.indexOf(item.functions[key])>1){
ars.push(item.functions[key])
}
}
console.log(ars)
return <div key={index}>
<h2>{item.name}</h2>
{
ars.map((i)=>(
<p>{i.name}</p>
))
}
</div>
})
}
</div>
I need to get values like this:
some1
some3
So I need to get only one name from property string. And for number there is only one name.
You could create a Set for property. If a property hasn't been added yet, add the name for the property to the array.
const arr = [{
name: 'name1',
functions: {
0: {
name: 'some1',
property: 'string'
},
1: {
name: 'some2',
property: 'string'
},
2: {
name: 'some3',
property: 'number'
}
}
}]
const propertySet = new Set,
names = []
for (const { functions } of arr) {
Object.values(functions).forEach(o => {
if (!propertySet.has(o.property)) {
names.push(o.name);
propertySet.add(o.property)
}
})
}
console.log(names)
If uniqueness based upon the string representation of the value of property is enough and the value of name is always truthy you can use the following code:
const arr = [{name: 'name1', functions: {0: {name: 'some1', property: 'string'}, 1: {name: 'some2', property: 'string'}, 2: {name: 'some3', property: 'number'}}}];
let lookup = {};
arr.forEach(obj => {
Object.values(obj.functions).forEach(func => {
lookup[func.property] || (lookup[func.property] = func.name);
});
});
console.log(Object.values(lookup));
Note: This solution sees property: 123 and property: "123" as the same value, since the string representation is used. If the following is an option name: "", name: null, etc. then the first truthy name is used, if there is no truthy name present the last occurrence of name is used instead.

Check if one element exists in an array of objects

I have the following array of objects:
var memberships = [
{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
How can I verify if such an array has at least one element with type 'member'?
Note that the array can also have no elements.
Use array.some()
var memberships = [{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
var status = memberships.some(function(el) {
return (el.type === 'member');
});
/*
// Simplified format using arrow functions
var status = memberships.some(el => el.type === 'member')
*/
console.log(status);
Array.some()
Array.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value. If such an element is found, some() immediately returns true. Otherwise, some() returns false.
You can use Array#some method:
const memberExists = memberships.some(member => member.type === 'member');
Then, if(memberExists) ...
I think this may help
let resultArray=memberships.filter(function(item) {
return item["type"] === 'member';
});
the result array holds the data of the objects that has type member
You can use Array#some
var memberships = [
{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
console.log(memberships.some(m=>m.type==='member'));
You can also use find, which returns the first object if found else undefined.
let a = memberships.find(o => o.type === 'member');
if (a) {
...do something
}
var memberships = [
{
"Name": "family_name",
"Value": "Krishna"
},
{
"Name": "email",
"Value": "harikrishnar88#gmail.com"
}
];
let resultArray=memberships.filter(function(item) {
return item["Name"] === 'email';
});

How to get parent property in JS object?

Not sure if title is formulated correct, but I have a JS object that looks like:
parent:{
children:[
{
id: "1"
user:[
{
id: 'aa',
email:'aa#google.com'
},
{
id: 'b',
email:'bbb#google.com'
},
]
},
{
id:"2",
user: [
{
id:'aa',
email:'aa#google.com'
},
{
id:'eee',
email:'eee#google.com'
}
]
}
]
}
The object is way bigger but follows the above structure.
How would I go to get a list of topics each user is on, filtered b ID?
E.g. 'aa' participates in children 1 and 2
'b' participates in child 1
etc.
I figure it out I have to map the object but not sure how to proceed after that
Assuming, you want an object with participant as key and all topic id in an object, then you could iterate the arrays an build a property with the associated id.
var data = { project: { topics: [{ id: "1", participants: [{ id: 'aa', email: 'aa#google.com' }, { id: 'b', email: 'bbb#google.com' }, ] }, { id: "2", participants: [{ id: 'aa', email: 'aa#google.com' }, { id: 'eee', email: 'eee#google.com' }] }] } },
result = Object.create(null);
data.project.topics.forEach(function (a) {
a.participants.forEach(function (b) {
result[b.id] = result[b.id] || [];
result[b.id].push(a.id);
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can write a function like this one:
function findTopicByID(id) {
let findedTopic = {};
let topics = obj.project.topics;
topics.map((topic) => {
if(parseInt(topic.id) === id) findedTopic = topic;
});
return findedTopic;
}
This function return the finded topic with the corresponding id or an empty object.
You can loop the topic array and build a new resulting array of users, if a user already exist then just update the users topic list, else create a new user with name, email, and a topic list.
let result = [];
project.topics.forEach((t) => {
t.participants.forEach((p) => {
let found = result.find((r) => r.name === p.id);
if (found) {
found.topics.push(t.id);
} else {
result.push({
name: p.id,
email: p.email,
topics: [t.id]
});
}
});
});
so now when you have the resulting array, you can just find a user and get which topics she participates in
let aa = result.find((r) => r.name === 'aa');
console.log(aa.topics);

Categories