I'm working on existing Javascript code, which uses datasets stored in objects which are named data1, data2, etc. The numbers are IDs taken from a database.
Now, I need to write a little additional function which takes the IDs as input, then constructs the appropriate object name using that Id, and then passes that object to a function as a parameter.
So, something like:
function doStuff(id){
var objname="data"+id;
//now, I need to pass the object (not just the name) to a function
someFunction(objname); //this obviously doesn't work, because it just passes the object name as a string
}
So, how do I pass the actual object to the function, given that I have the object name?
The question sounds elementary, and I assume there's a method which does just this, but google doesn't seem to help.
Since the objects exist, you need a way to "find" them. I suggest you create a relationship between the string and the object using a key-value array - the key is the string, and the value is the object. You can then index the array with the string, and it will return the object.
Create an object and store in it keys like so:
var obj = {
data0 : "example 1",
data1 : "example 2"
}
Then you can access the properties like so:
function doStuff(id) {
var key = "data" + id;
someFunction(key);
}
someFunction(key) {
return obj[key];
}
Related
So, I'm trying to figure out how I can return the name of an object from a for loop. It seems that whenever you push an object into an array, the name seemingly vanishes, and whenever I run a for loop, I can never get the name to show. For example:
/* I know this is a variable, but I'm asking about this for something like a fetch, where the returned json is a list of objects. test is just an example name for those objects returned from the fetch. */
let test = {
hi: 'hi'
};
let arr = [];
arr.push(test);
/* Here, I wish for the name of the objects, like if from a fetch we have an object test: {hi: 'hi'} from a fetch, and I put that into a for loop, I want to be able to extract the name of that object and use it, instead of the only things being accessible are the object entries */
for (let count in arr) {
console.log(arr[count])
};
Here, the name of the object will suddenly vanish, and there's no getter inside the object to return the name. In this example, my goal would be for 'test' to be returned. Without having a getter inside the object for the name How can I get some sort of list of objects, and put those objects in a for let loop that will actually return the name of the objects inside the loop--if there even is a way?
If you want to store a name/value list, use an object
let obj = {"test": {hi: "hi"}};
Object.entries(obj).forEach(([key, value]) =>
console.log(`${key} = ${JSON.stringify(value)}`)
);
Print out your count variable. It is what you are looking for.
It should better bet named key instead
The test is a variable name that only holds the referance of the object in the memory, but it's not the name of the object, if you need to have each object have its own name, I suggest you add name property in the object.
let test = {
hi: 'hi',
name: 'test',
};
let arr = [];
arr.push(test);
for (let count in arr) {
console.log(arr[count].name);
};
For example when you have an object
const obj = {
time,
difficulty,
distance,
}
The values that are inside of the object are saved as keys, correct?
If I was to call Object.keys() on the object I would receive array of individual string elements?
Using that notation, the property name will be the key, and the property value will be the value. This syntax was introduced in ES6.
It is the same as
const obj = {
'time': time,
'difficulty': difficulty,
'distance': distance
}
When you call Object.keys() it returns an array of the property names, not their values.
You can use an object like an associative array to make it act like a key/value pair.
someObject[“someKeyName”]
I have an object inside an object, the name of the object could change, how can I get the value inside of the object's object without referring to it by name?
Object {medium-editor-1453741508068-0: Object}
medium-editor-1453741508068-0: Object
value: "this is what i want"
This gets the above:
this.mediumEditor.editor.serialize();
I need something like:
this.mediumEditor.editor.serialize().childObject.value;
If your top-level object only contains one object, you can simply use Object.keys(topLevelObject) to get the "object's object" name. Something like the following:
var objectsObjectName = Object.keys(topLevelObject)[0];
var value = topLevelObject[objectsObjectName].value;
The same logic can be used recursively if you have more levels of object nesting, or if the object's object's value's name (wow, this is getting hard to follow) is non-predictable too.
You can also iterate on the top-level object:
for (var key in topLevelObject) {
var value = topLevelObject[key].value;
}
This works even if you only have one nested object, even though it's arguably weird to write a loop knowing it will only loop once.
Convert this:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}
To this:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"} that is... {id: quantity}
I found an answer that almost does what I need: Searching for an Object inside the JSON. But that answer doesn't help me because it's only at the first level (one json object). My problem is at the second level (json object within a json object). Thanks in advance!
It helps if you don't think of JSON objects as JSON objects. Once you run a JSON string through JSON.parse, it is a native JavaScript object.
In JavaScript, there are two ways to access objects.
Dot Notation
The dot notation goes like this
myObject.name
See the dot? You can use that to access any object property (which indeed may be another object in javascript, as long as it has a valid dot notation name). You can't use characters like -, ., and the space character.
Bracket Notation (may be another name)
myObject["variableName"]
Like dot notation but allows some other characters, like - and the space character.. Does exactly the same thing.
Using these notations is useful because we can access nested properties.
myObj.foo.bar.baz()
Now let's get to your JSON object...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
You might want to brush up on the JSON format yourself, but in your example, here's a few clues...
{ Means the start of an object. (Keep in mind your entire JSON string is an object itself.)
} Means the end of an object.
"variable" (with quotes! important in JSON, but not when accessing/declaring javascript objects) assigns a property to your object.
: Is the assignment operator in both JSON and JavaScript objects.
Anything to the right of the : is the value you are assigning to the property on the left.
, Means you are starting a new property within an object.
You probably know that [] with , commas inside means an array.
When we run your string through JSON.parse(string), we'll get an object that looks like this...
var myResponse = JSON.parse(response);
You can now use it as a native JavaScript object. What you're looking for is a nested property within "items".
var items = myResponse.items; //alternatively you could just use myResponse.items
Since items is an array of objects, we'll need to iterate through it in order to convert the existing object into a new object.
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.
Result is now an object that looks like:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}
You can access the properties using bracket notation.
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
You can try with:
var obj = {
"items":[
{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}
],
"country":"JUS",
"region":"A",
"timeout":"FILLER"
};
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
quantities will then be the object {"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}. forEach is a native method of array objects in JavaScript that lets you iterate through their elements. You may want to put that piece of code inside a function:
function getQuantities(obj) {
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
return quantities;
}
You need to do the following:
var newJSON = {};
for (var i = 0; i < oldJSON.items.length; i++) {
newJSON[oldJSON.items[i].id] = oldJSON.items[i].quantity;
}
In my script there is a need to create a hash table, and I searched in google for this. Most of the folks are recommending JavaScript object for this purpose. The The problem is some of the keys in the hash table have a "." in them. I am able to create these keys easily with the associative arrays.
I don't understand why associative arrays are bad. The first thing that is mentioned on the sites that I looked at is the length property.
I am coming from the Perl background, where I used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair. If these are my common uses, can I safely use an associative array?
In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:
var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';
alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'
If you're using them already and they work, you're safe.
In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:
var obj = {"my.key": "myValue"};
vs.
var obj = [];
obj["my.key"] = "myValue";
Therefore never use the array object for this, but just the regular object.
Some functionality:
var obj = {}; // Initialized empty object
Delete a key-value pair:
delete obj[key];
Check if a key exists:
key in obj;
Get the key value:
obj[key];
Add a key-value pair:
obj[key] = value;
Because there is no such thing as built-in associative arrays in JavaScript. That's why it's bad.
In fact, when you use something like:
theArray["a"] = "Hello, World!";
It simply creates a property called "a" and set its value to "Hello, World!". This is why the length is always 0, and why the output of alert(theArray) is empty.
Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript. Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype.
So, a Perl hash and an ECMAScript object behave similarly. You might not know that you can access object properties not only via a dot, but also with brackets and strings, like
var myObj = { foo: 42 };
myObj.foo; // 42
myObj['foo']; // 42
Knowing that, you can also use keys with .
var myObj = { };
myObj['hello.foo.world'] = 42;
Of course, you can access that key only with the bracket notation.
You can use . in key names on JavaScript objects (AKA associative arrays) if you'd like; they're accepted without issue. The minor drawback is you can't use shortcut notations with the dotted keys, e.g.
var x = {};
x['hello'] = 'there';
alert(x.hello);
is perfectly acceptable and will pop up an alert with 'there' in it. But if you use a dotted name:
var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);
will fail, as JavaScript will look for an attribute named this in the x object, which does not exist. There is only the this.is attribute.
There isn't an associative array. It's just an object.
foo.bar; // Equivalent to...
foo["bar"]; // Looks like associative array.
For the sake of convenience of using data, there should be no difference between an object and an array. You can think of it as an object or you can think of it as an associative array. At the end, you can just think of everything as data.
For PHP, [ ] accepts 0, 1, or more items(array), and it is called an associative array. It is JSON in PHP's coat:
$data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];
For JavaScript, { } accepts 0, 1, or more items(array), and it is called an object. This data format is JSON:
data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};
I just call them data. The simplest way to describe data is JSON, or its variants.