Creating json objects to exclude undefined properties - javascript

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...

Related

Can't get the value from an object properly. (TypeError: Cannot read property 'filter' of undefined)

I am trying to make a search box which filters some data (object) when users put search term and display the result.
This is the code.
state = {
names: customerData.name,
searchTerm: ''
};
editSearchTerm = (e) => {
this.setState({searchTerm: e.target.value})
}
dynamicSearch = () => {
return this.state.names.filter(name =>
name.toLowerCase().includes(this.state.searchTerm.toLocaleLowerCase()))
}
This is the data.
customerData = [
{
"index" = 0,
"age" = 20,
"name" = "A"
},
{
"index" = 1,
"age" = 30,
"name" = "B"
}
]
when I execute the code it returns an error message "TypeError: Cannot read property 'filter' of undefined".
Looks like
names: customerData.name
is not the right way of getting the value of the data. What is the correct way to get the value from it?
When you define the state, give an empty array [] to names.
state = {
names: [],
searchTerm: ''
};
And change the names state when you get the customData. Don't forget to check if customData.names is a valid array. Please check if customData.names is returning array.
if (customData.names) {
this.setState({
names: customData.names
})
}

How to check instance of key which is present inside object

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
}

Object is not getting returned instead main array return

I am facing an issue while returning an object from the array using map function .
I have an array of object which looks like
const data={
"Sessions" :
[{"id" : "2", "Name":{"firstName": "jonas", "lastName":"parker"}}
, {"id" : "3", "Name":{"firstName": "peter", "lastName":"donl"}}, {"Id":
1,"Name":{"firstName": "xyz", "lastName":"abc"}}]}
Now, I am trying to return the object
const active = data?.Sessions ?? [].map((session) => {({label:
`${session.Name.firstName}`, value: `${session.Name.lastName}`}))
So, I was expecting it return an array of object which will have label and name as keys and their respective values.
So, I am getting the data?.Sessions array in return i.e. original array of object which I am using for iterating.
Can any one help me with this ?
Thanks.
Just use Array#map on data.sessions. You are currently using the null coalescing operator so that map is only called if sessions is not null or undefined, and on an empty array, at that.
const active = data?.Sessions.map((session) => ({label: `${session.Name.firstName}`, value: `${session.Name.lastName}`}));
You are using the Nullish Coalescing Operator in your active variable.
That means the active variable will get the left hand side value, data?.Sessions because it is not null or undefined.
Also, you are iterating the over an empty array: [].map on the right hand side of the assignment.
Try this:
const active = data?.Sessions.map(function(session){
return {
label: session.Name.firstName,
value: session.Name.lastName
}
})```
Here is an array of label and value:
const data={
"Sessions" :
[{"id" : "2", "Name":{"firstName": "jonas", "lastName":"parker"}}
, {"id" : "3", "Name":{"firstName": "peter", "lastName":"donl"}}, {"Id": 1,"Name":{"firstName": "xyz", "lastName":"abc"}}]}
let active = (data?.Sessions ?? []).map((session) => ({label: session.Name.firstName, value: session.Name.lastName})
)
console.log(active)

Check if item value exists in Firebase array

{
"accounts" : {
"-account1" : {
"email" : "test#example.com",
"name" : "John doe",
"online" : false,
"profilePic" : "example.com/img.png",
"username" : "jonh_doe"
"tokens" : [
"token11111",
"token22222",
"token33333"]
},
"-account2" : {
"email" : "testymctest#example.com",
"name" : "Jane doe",
"online" : false,
"profilePic" : "example.com/img.png",
"username" : "jane"
"tokens" : [
"token44444",
"token55555",
"token66666"]
}
}
}
My user data is structured as above and I'm trying to determine if -account1 has a token with the value "token11111"
Other Firebase examples suggest using snapshot, but I haven't found an example that drills down into a child element to find a value.
This is what I've tried
firebase.database().ref('accounts/-account1/tokens')
.equalTo(newToken)
.once('value')
.then(function(tokens) {
if (tokens.exists()) {
//Token already exists
}
else{
//Push new token to db
}
});
When you get an array-like object back from a Firebase snapshot (the keys are numbers starting a 0), you deal with it just like a regular JavaScript array:
var ref = firebase.database().ref('/accounts/-account1/tokens');
ref.once('value').then(function(snap) {
var array = snap.val();
for (var i in array) {
var value = array[i]
console.log(value);
if (value == 'whatever') { ... }
}
});
This will iterate and print each value. You can look for any value that you like in that loop. Or you can includes(x) on the array in JavaScript ES2016.

Using objects to store a list of names

I was wondering how to use an object to store a list of different names and access them by simply using the key.
Do I have to use embedded object like this.
var f =
{
0 : { name : "John" },
1 : { name : "Phillip" }
};
console.log(f[1].name);
Do not over-complicate things. Why don't you just try a simple array?
var f = [
{ name : "John" },
{ name : "Phillip" }
];
console.log(f[1].name);
Why not just an array, which is indexed identically? Do you actually need a name: attribute for some reason?
var names = [ 'John', 'Phillip' ];
Instead of names[0].name, which is pretty redundant, you'd just use names[0]...
He wants to access them by key:
var people = {
John:{ age:33},
Bob :{ age:42}
};
Now you can truly access them by key:
console.log(people["John"].age);
or this way (although odd):
console.log(people.John.age);
No looping is necessary, you are using the power of javascripts associative syntax to index directly into your data structure. No need to refer to some arbitrary integer index either.
This definitely works but typically you'd use a more appropriate property to index than just a name like perhaps an employee id.
You can use like this
Var names = [
{ 'name' : 'ashwin', age: 18 },
{'name' : 'jhon', 'age' : 20 }
];
console.log ( names[0].name );

Categories

Resources