I have object as,
var obj = {
a: {
username: 'xyz',
picture: {
value: "",
id: "",
},
},
};
here keys of picture object is dynamic(means picture object do not have same keys always), which change every time. I just want to check whether obj have any instance of Date. How I can check the whether obj have any instance of Date in js?
You can check if the key is not undefined this way:
if(obj.a.picture.date){...code if 'date' exists} else {...code if 'date' not exists}
You can try like this:
{obj.a?.picture &&
Object.keys(obj.a.picture).findIndex(key => key === 'Date') > -1
? obj.a.picture["Date"]
: null
}
Related
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
How do I search for a specific value in an array of objects based on another value? For example, I have the ID of a post and want to check if I have the required permissions for that particular Post ID.
Posts = [
{
Id: '123',
Permission: 'True',
Name: 'XY'
//Other key value pairs
},
{
Id: '456',
Permission: 'False'
Name: 'AB'
//Other key value pairs
}
];
My current approach goes in this direction.
if (posts.some(e => e.Permission === true && e.Id == PostId)) {
return true;
} else {
return false ;
}
I appreciate any support.
To find the element
const arr = arr.find(p => p.property == someValue);
This will return undefined if the element is not found and return the element if found.
To find the index of the element
If you only want the index use findIdex
const index = arr.findIndex(p => p.property == someValue);
If the element is not found it will return -1 and if found return the index.
To check if the element is present i.e bool value
Your current implementation does that. You can simply return that.
return posts.some(e => e.Permission === true && e.Id == PostId)
Seems like you are confusing with how to use the value from somewhere else to search in the array, you can always pass in a callback and check that.
value => value.somProp == value1 && value.otherProp == value2 || someOtherChek(value)
you can use filter
Posts = [
{
Id: '123',
Permission: 'True',
Name: 'XY'
//Other values
},
{
Id: '456',
Permission: 'False'
Name: 'AB'
//Other values
}
];
let id='123';
let filtered=Posts.filter(i=> i. Permission===true && i.Id===id);
I have an object like this:
The thing I want to do is to rename the services.XXX value but keep his child properties.
For example I want to rename object.services.cadvisor with object.services.new-name
How can I do that ?
You can do the following
object.services.newName = object.services.cadvisor;
delete object.services.cadvisor
Copy the object to the new property and delete the old one
let myObj = {
services: {
cadvisor : {
name: 'Cadivsor',
length: 50,
nestedObject : {
name: 'Nested'
}
},
other : {}
}
};
myObj.services['newName'] = myObj.services.cadvisor;
delete myObj.services.cadvisor;
console.log(myObj);
I have the following snippet code which, within a loop, creates a JavaScript object where some of the properties maybe undefined:
reader.on('record', function(record) {
let p = record.children;
let player = {};
// below we create a dynamic key using an object literal obj['name'], this allows use to use
// the id as the firebase reference id.
player[p[0].text] = {
id: parseInt(p[0].text, 10) || "",
name: p[1].text || "",
country: p[2].text || ""
};
};
My question therefore; is there a better way for creating this object via a 'Map' for example? If the properties are undefined then do not add them to the object.
Note: This data is being sent to a Firebase DB, so any undefined values throw an error -- my crude (but working) approach is to add them as an empty string.
Here is a sample of the JSON I would like to see (notice country is not missing from the second player):
{
"players" : {
"100001" : {
"id" : 100001,
"name" : "Matt Webb",
"country" : "ENG"
},
"100002" : {
"id" : 100002,
"name" : "Joe Bloggs",
}
}
null values are not set in Firebase and don't give you error
player[p[0].text] = {
id: parseInt(p[0].text, 10) || null,
name: p[1].text || null,
country: p[2].text || null
};
You can do something like this:
player = JSON.parse(JSON.stringify(player));
This way, you can use...
player[p[0].text] = {
id: parseInt(p[0].text, 10),
name: p[1].text,
country: p[2].text
};
... and don't worry with undefined values, because JSON.stringify doesn't serialize keys with undefined values...
Wit this example object:
obj = {
id: '123',
attr: 'something'
}
Now I want to add the attribute link in the attribute data. Sometimes data is already existing, but in this example data doesn't exist.
So if I do
obj.data.link = 'www.website.com';
I get the error TypeError: Cannot set property 'link' of undefined.
Result should be:
obj = {
id: '123',
attr: 'something',
data: {
link: 'www.website.com'
}
}
You need to create the data object first:
obj.data = {};
obj.data.link = 'www.website.com';
or you can do it all at once:
obj.data = {
link: 'www.website.com'
};
if data may or may not already by there, there's a handy shortcut that will use the existing one if it's there or create a new one if not:
obj.data = obj.data || {};
obj.data.link = 'www.website.com';
That uses the JavaScript's curiously-powerful || operator.
You need to initialize the data property. You can do something like this:
var obj = {
id: '123',
attr: 'something'
};
obj.data = {};
obj.data.link = 'www.website.com';
In the case for the property existing you can check before assigning link.
if (!obj.data) {
obj.data = {};
}
And as stated in another answer you can use the or operator which I've heard is 'curiously powerful' =]
obj.data = obj.data || {};
That basically means if this value ( obj.data ) exists use it and if it doesn't use the right operand ( {} ). This works because of short circuit evaluation.
Javascript From 1.8.5 you can use the following method:
Object.defineProperty(obj, "data", {
value: {'link' : 'www.website.com'},
writable: true,
enumerable: true,
configurable: true
});
Good luck :)
I'm planning to make a collection to hold different app-wide settings, like, say, amount of logged in users today, Google analytics tracking ID, etc. So I made a schema like this:
options_schema = new SimpleSchema({
key: {
type: String,
unique: true
},
value: {
},
modified: {
type: Date
}
});
Now the main problem is that I want value to be of any type: Number, String, Date, or even custom Objects. Though it has to be present, can't be null.
But of course it gets angry about not specifying the type. Is there a workaround for this?
You can use Match patterns for your fields' type which allow you to do pretty much anything :
const notNullPattern = Match.Where(val => val !== null)
value : {
type : notNullPattern
}
(See Arrow functions)
Note that this will allow everything but null, including undefined.
Defining patterns this way allow you to use them everywhere in your application including in check :
check({
key : 'the key',
modified : Date.now(),
value : {} // or [], 42, false, 'hello ground', ...
}, optionsSchema)
Match.test(undefined, notNullPattern) //true
Match.test({}, notNullPattern) //true
Match.test(null, notNullPattern) //false
A more general solution to exclude one value would simply be:
const notValuePattern =
unwantedValue => Match.Where(val => val !== unwantedValue))
The use of which is similar to the above:
Match.test(42, notValuePattern(null)) // true
Note that due to the use of the identity operator === it will notably fail for NaN:
Match.test(NaN, notValuePattern(NaN)) // true :(
A solution could be:
const notValuePattern =
unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
!Number.isNaN(val)
: val !== unwantedValue
)
Should you want a solution to exclude some specific values in a schema (kind of the contrary of Match.OneOf), you could use the following:
const notOneOfPattern = (...unwantedValues) =>
Match.Where(val => !unwantedValues.includes(val)
)
This uses Array.prototype.includes and the ... spread operator. Use as follow:
Match.test(42, notOneOfPattern('self-conscious whale', 43)) // true
Match.test('tuna', notOneOfPattern('tyranny', 'tuna')) // false
Match.test('evil', notOneOfPattern('Plop', 'kittens')) // true
const disallowedValues = ['coffee', 'unicorns', 'bug-free software']
Match.test('bad thing', notOneOfPattern(...disallowedValues)) // true