Using objects to store a list of names - javascript

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 );

Related

Add object to another object property in JS

obj={
cats:{name:"kitty",age:"8"}
}
I need to add {name:"nacy",age:"12"} to obj.cats how I can do that?
What I tried:
Object.assign({name:"nacy",age:"12"},obj.cats);
This doesn't do anything, when I console.log(obj) I got kitty only.
In the end I want when I console.log(obj.cats) to get this:
{name:"kitty",age:"8"}, {name:"nacy",age:"12"}
And I don't want to use arrays.
It would be advisable to read more the documentation on objects and arrays. object.cats should be an array. Correct usage:
let obj = {
cats: [
{name:"kitty",age:"8"}
]
};
obj.cats.push({name:"nacy",age:"12"})
//Now here, we have 2 elements of obj.cats
console.log(obj.cats)
If you want to use objects and replace obj.cats (as your example), you must first pass the existing object, and then the value to replace: Object.assign(obj.cats, {name:"nacy",age:"12"})
if you wanna add 'nacy' first you have change cats to become an array
(read more about array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
it looks like this:
var obj={
cats:[{name:"kitty",age:"8"}]
}
and then 'push' or add 'nacy'
obj.cats.push({name:"nacy",age:"12"})
result :
{ cats: [ { name: 'kitty', age: '8' }, { name: 'nacy', age: '12' } ] }

Dexie : How to add to array in nested object

I am using Dexie IndexedDB wrapper and I am trying to add an object to an existing array which in inside a nested object. The structure looks similar to below
{
Name : 'John',
age : 33,
tags : {
skill: [{
first: '.NET',
second: 'JAVA',
third: [{special1:'sleep'},{special2:'eat'}]
}]
}
}
I have tried many way to push object special3:'run' to skill.third but without success. My last attempt looked something like this
const pathObject = {};
const fullPath = 'result.tags.skill[3].third';
pathObject[fullPath] = {special3:'run'};
db.inspections.update(id, pathObject);
The object is added outside and not inside the array 'third' something like below
{
Name : 'John',
age : 33,
tags : {
skill: [{
first: '.NET',
second: 'JAVA',
third: [{special1:'sleep'},{special2:'eat'}]
}]
skill[3]: {
third: {special3:'run'}
}
}
}
I wish to know if there a way to add to arrays in nested object using Dexie if not is there a way to achieve this using indexeddb. Help is appreciated as problem is been holding back progress
The easiest is to use Collection.modify() with a callback function to mutate your model:
db.inspections.where('id').equals(id).modify(x =>
x.tags.skill[0].third.push({special3:'run'}) );
If you want to use a keypath containing array items, it is also possible, as arrays can be looked at as objects with numeric keys:
db.inspections.update(id, {"tags.skill.0.third.3": {special3:'run'}});

Creating json objects to exclude undefined properties

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

Create a JSON object with variables as fields

I want to create a JSON object with variables as associative variable names similar to the following:
var field = 'first';
var query = { details.field, details.field };
I would prefer if the details were a fixed value.
This is my dataset currently
{
field1: ,
group: {
first:
}
}
My question is, how would I go about creating JSON objects with variables as fields?
You can add a property to an object like so:
var query = { details: {} };
var field = 'first';
query.details[field] = "TEST";
Which will give you the object:
{ details: { first: "TEST" }}
which you can then access with query.details.first or query.details[field];
Is that what you're looking for?
A simple way to accomplish this in Javascript is using the . operator.
query.details.field = "first";
This will product an object as follows:
"query" { "details" { "field": "first"} }
Is this what your looking for?
If you want multiple details you will want to use an array.
var query = [];
query.push({"details" { "field" : "first"} });
query.push({"details" { "field" : "second"} });
This will product an object like this
"query" [
"details" { "field" : "first"},
"details" { "field" : "second"}
]

Extended function jquery

I have a function that looks like this:
jQuery.fn.menuFunc = function( settings ) {
settings = jQuery.extend({
actionAddURL:"",
actionModifyURL:"",
........
},settings);};
where all the parameters i initialize (actionAddURL, actionModifyURL, etc..) are strings (ids of different elements or urls). My question is how do i add some objects there.
myObject:"" doesn't seem to be the way to do it. Any tips?
myObject:[] // empty JavaScript object
,
myOtherObject: { // JavaScript object notation
name: "Bob",
age: 17
}
Probably:
myObject: {}
is what you are looking for.
You can then add properties to it:
myObject.name = "Name";
To define an object you could use the following syntax:
myObject: { stringProp: 'value1', intProp: 10, arrayProp: [ 1, 2, 3 ] }

Categories

Resources