How do I define an object variable structure in JavaScript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to define something like the following object structure, so I can populate it from a number of sources. What statements do I need to define it?
Offices[] is an open-ended array as is rel[] underneath it. All the elements are strings or maybe numbers.
Offices.name
Offices.desc
Offices.rel.type
Offices.rel.pt

First I would make Offices an array:
var Offices = [];
Then populate that with objects:
var obj = {
name: "test",
desc: "Some description",
rel: []
}
Offices.push(obj);
Now you have your array (Offices) populated with one object, so you could access it via Offices[0].desc -- you can also populate the rel array with Offices[0].rel.push(anotherObj)

If i understand correctly, you want to place multiple objects of the same type inside the Offices array. In order to easily build multiple objects of the same type you could use a constructor:
function Office(name, desc, rel){
this.name = name;
this.desc = desc;
this.rel = rel;
}
Now you can declare an array to hold instances of the above type:
var offices = [];
And you can add new instances like this:
offices.push(new Office('John', 'good guy', []));
You can apply the same idea to the rel array to enforce the structure of the objects, or simply use object and array literals:
offices.push(new Office('John', 'good guy', [{ type : 'M', pt : 3 }, { type : 'Q', pt : 2 }]);

Related

Is it possible to dynamically add key:value pair to JS objects? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
Suppose I have a JS object zoneJSObject which has a structure like this:
zoneJSObject = {"ZoneWidgets" : ""}
when creating this object I don't know how many ZoneWidgets I'll have. So I can't pre-define a set structure for them. ZoneWidgets will be a array of integer id's eg. "123456789", further on I want to acquire coordinates for each of these widgets. So ZoneWidget 123456789 will have 4 key:value pairs top,bottom,left,right how can I add these under the specific widget?
data = "111222.333"
zoneJSObject[0].ZoneWidgets[0] = "123456789"
zoneJSObject[0].ZoneWidgets[0].top = data // tried adding it like this but got this error
Uncaught (in promise) TypeError: Cannot create property 'top'
ZoneWidgets will be a array of integer id's eg. "123456789", further on I want to acquire coordinates for each of these widgets. So ZoneWidget 123456789 will have 4 key:value pairs top,bottom,left,right how can I add these under the specific widget?
You will need your ZoneWidgets to be an array of objects if you wish to assign your key-value pairs and an integer:
ZoneWidgets = [
{ id: 1234 },
{ id: 5678 },
];
Later:
ZoneWidgets[0].left = myLeft;
ZoneWidgets[0].right = myRight;

dot character in property name [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I got this code snippet from jest documentation.
In the example, one of the variables is named ceiling.height and is the only variable with a dot . in the name. What would be the purpose of using variables with a dot in the name such that it warrants this example in the documentation?
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
'nice.oven': true,
},
'ceiling.height': 2,
};
The purpose would be to store nested objects in a flat format, ie. a database table.
You could use something like dottie.js to transform this flat object into a nested object
const values = {
'user.name': 'Gummy Bear',
'user.email': 'gummybear#candymountain.com',
'user.professional.title': 'King',
'user.professional.employer': 'Candy Mountain'
};
const transformed = dottie.transform(values);
We would now find this to be the value of transformed
{
user: {
name: 'Gummy Bear',
email: 'gummybear#candymountain.com',
professional: {
title: 'King',
employer: 'Candy Mountain'
}
}
}
Why they use it like that in the example seems to be so that they can provide an example (below) on how to access these kinds of variable names. Imagine that you wanted the .toHaveProperty(keyPath value?) function from the Jest docs to operate on a property in the values object from the above example. This shows you how you might use this function with such a property.
// Referencing keys with dot in the key itself
expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
Unless you have a very good reason, using these kinds of variable names is not a best practice and I would not recommend it. That said, while a variable name with a . character is not able to be used with dot syntax:
houseForSale.ceiling.height = undefined
It is still accessible with bracket syntax:
houseForSale['ceiling.height'] = 2

How can i create an array of objects in which each object has 4 values? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to create an array of objects in which each objects has 4 values. All coming from 4 diferent arrays.The arrays are long.I have no idea on how to do it. It's pretty difficult i think, i have been looking for hours vv'.
var local=[F.C Barcelona, Real Madrid, Manchester United.....];
var away=[ Manchester City, PSG, Liverpool....];
var matchDay[2,3,4,5....];
var score=[2-0, 0-1, 2-2...];
// array to hold the objects
let arr = []
// assuming the four arrays are all the same length
// just pick one to use for the length
for(let i = 0; i < local.length; i++) {
// create a new object with the 4 fields, one from each array
// and grab the i'th entry of each array for it
let obj = {
local: local[i],
away: away[i],
matchDay: matchDay[i]
score: score[i]
};
arr.push(obj);
}
Not sure exactly what you're trying to do, but something like this would work.
> array1.map(function(item, index){
return {key1: item,
key2: array2[index],
key3: array3[index]
};
});

What is the best way to group data pairs in javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Instead of using associative arrays (objects), what is the best way to associate two values so they are always associated and can both be accessed as separate values? Associative arrays are annoying because their order isn't guaranteed and you can't access them using indexes.
I could create two separate arrays but if I randomize their order for display their association would not match, and if they are separate in code there is a good chance I can make a mistake when recording their values, putting them in the wrong order so they don't perfectly match up.
In Javascript you can use multidimensional arrays:
var data = [
[1, 2],
[3, 4]
];
data[0][0]; // get '1'
data[0][1]; // get '2'
Also if you need to associate data in a more abstract way, ES6 has WeakMaps:
var wm = new WeakMap();
var x = document.createElement("div");
wm.set(x, {foo: 1, bar: 7});
console.log(wm.get(x).bar) // get '7' from object you associated to HTMLElement
I do not now which kind of data you should store but maybe you could try to store data in a single variable in this way:
var data = [];
data[0] = "Test" + "|" + Value;

How to find that particular array Item is present or not Using JQuery + Backbone.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Each ArrayItem contains no. of Property like Id, Name, Description etc
But we want to Fetch ArrayItem with Help of Name Property .
So Please give me code suggestion in Jquery or backbonejs without using for loop.
If you are using BackboneJS, you already have UnderscoreJS installed. Underscore has several methods for searching through a collection. For instance, using _.findWhere(...):
var myArray = [ ... ];
var helpItem = _.findWhere(myArray, { name: 'help' });
This would return the first entry in the array that has a name property equal to 'help'. _.findWhere(...) can match multiple properties too. If you want to find an item with something other than direct equality of properties, you can use _.find(...):
var overTwentyOne = _.find(myArray, function(entry) {
return entry.age > 21;
});
This would return the first entry in the array whose age property was greater than 21.
Note also that most of the list-centric methods in Underscore are automatically mixed into all Backbone.Collection instances. So if you were searching through a Collection, the above findWhere(...) example could be more simply written as:
var helpItem = collection.findWhere({ name: 'help'});
This would return the first Backbone.Model instance from collection that had a property name equal to help.

Categories

Resources