Set value to non existing object - javascript

Say i have this object:
test = {
testObj: {
"1": {
"key": "value"
}
}
}
And i want to add values to testObj like so:
test.testObj["2"].key = "my value";
I get error TypeError: Cannot set property 'key' of undefined
Now i do understand that key does not exist yet, but 2 doesn't exist also, and yet i can set value to it:
test.testObj["2"] = "something";
So what can i do about it?
EDIT
wow i feel stupid for not figuring that out by myself... anyways thank you guys.

Javascript doesn't know what test.testObj["2"] should be in this scenario, so it ends up testing it as an existing property:
test.testObj["2"].key = "my value";
The assignment can only apply to the last part of the structure on the left.
But you can tell it what it is by creating the object first:
test.testObj["2"]={};
test.testObj["2"].key = "my value";
Or in a single step:
test.testObj["2"] = { key: "my value"};

Related

Get object value that has numeric key in react native

I getting data as object like below:
{
"Version": "AAA",
"Schema" : "AAA",
"Total" : 432234,
....
"Content": {
"1" : {
"1" : {
...
},
"2" : {
...
},
...
}
}
}
How can I get the values from the numeric key in react native?
something like this:
var first_numeric_key = 1;
var second_numeric_key = 2;
aboveObject.Content[first_numeric_key][second_numeric_key];
I tried with the below script but still getting issues.
aboveObject.Content["1"]
TypeError: undefined is not an object (evaluating '_this4.state.contents.content["1"])
What is the best approach for this?
I am not a React Native guy but this seems more like a JavaScript syntax nuance.
You can access object keys as obj['key']
Here, in your case, it will be
aboveObject.Content['1']['2']
Updating answer after OP's edit to the question
const first_numeric_key = 1;
const second_numeric_key = 2;
aboveObject.Content[first_numeric_key.toString()][second_numeric_key.toString()];
EDIT
This is working without convert to the string
aboveObject.Content[first_numeric_key][second_numeric_key]
The issue was the exception handling, since there was some delaying when the app get the data from the fetch() function so the aboveObject was null at the very first time.

Accessing objects from within object?

This is probably a very newbish question, but I am learning javascript and working with pouchDB. I have a search function that returns something like:
{"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}
I can access the total_rows value easily obviously, but how would I access the value of 'text'?
Simply with x.rows[0].doc.text.
Edit: To help you understand a little better what's happening here, you're accessing "sub children" with the . operator. We're asking for the rows array inside x and then specifying we want the first row (remember that arrays are 0-indexed, meaning the first element in an array is at position 0).
From there, we just access the doc child, and the text attribute it contains.
var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};
console.log(obj.rows[0].doc.text);
Hi please cchecck this
var abc = {
"total_rows": 1,
"rows": [
{
"id": "mydoc",
"score": 0.7071067811865475,
"doc": {
"title": "Guess who?",
"text": "It's-a me, Mario!",
"_id": "mydoc",
"_rev": "1-21bd9b0c99791947618e98a23134b312"
},
"highlighting": {
"text": "It's-a me, Mario!"
}
}
]
}
console.log(abc.rows[0].doc.text);
console.log(abc.rows[0].highlighting.text);
it is better to identify each row by using 'id' to parse javascript object.
try this (javascript es6)
const obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}
const id = 'mydoc'
const text = obj.rows.find(item => item.id === id).doc.text
console.log(text)
javascript es5 or previous version
var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};
var id = 'mydoc';
var text = obj.rows.find(function(item) { return item.id === id; }).doc.text;
console.log(text);

Selecting a JSON object by number not by name

I try to store a JSON object with informations in multiple languages. Im not even sure they way i did it is good, any suggestions are welcome.
My current problem ist, that i dont know how to access the first language without knowing what language it is.
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
document.write(Data[1].Name);
I just want to access the second object, sometimes its "en", sometimes its "de".
Thanks for any tipps!
Here is a pure javascript solution:
First: You get the keys of the object:
var keys = Object.keys(Data);
Then: The keys are stored in a array. You can access them with an index. Like:
Data[keys[0]]
Now: You can use a foor loop or whatever you want :)
Data is an object its not array so you cant access it like Data[0] you can access it like Data.en.
but as you say you dont know any thing about en or de so i suggest that you form the Data object like this :
var Data =[{
lang:"en",
langData:{
Name:"Some name"
}
}]
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
var index = 0;
$.each(Data, function(key, val){
index += 1;
if (index == 2){
// key is the language, like in this example key is 'en'
console.log(key);
}
});
var name = (Data.en || Data.de || {})['Name'];
(Data.en || Data.de || {}) get's value of Data.en or Data.de if both doesn't exist, return empty object, so that script doesn't throw exception for Name property
()['Name'] same as myObject['Name'], myObject.Name
assign value to name variable, it will be Some name or undefined at least
If you have more languages, add them all, notice: it will return first found lang
var name = (Data.en || Data.de || Data.ru || Data.fr || {})['Name'];
Use Object.keys method to get list of object property names:
console.log(Data[Object.keys(Data)[1]]['Name']); // "Some name"

How to add a new item to struct in JavaScript?

I have a struct in JavaScript
settings = {
"type-1": {
"setting-1": true,
"setting-2": 2
}
"type-2": {
"setting-3": "value",
}
};
I can modify the items:
settings["type-1"]["setting-1"] = false;
But how can I add a new item in this struct?
Trying
settings["type-new"]["setting-100"] = "new one";
But settings["type-new"] is undefined. So how to add a new one?
you can do it on one line:
settings["type-new"] = {"setting-100": "new one"}
You need to set settings["type-new"] to an object first.
settings["type-new"] = {};
settings["type-new"]["setting-100"] = "new one";
Dogbert got it right, since you're using object literals (that's what they're called, not structs :P), you have to create them, before you can assign values to them. Doing settings["type-new"]["setting-100"] = "new one"; is equivalent to undefined["setting-100"] = "new one";. That's why it doesn't work.
On the side, you're really better off not using dashes in your keys, I find it easier to write code like yours along the lines of:
settings.typeNew.setting100 = "new one";
Which is more intuitive (the [""] notation is very serviceable in cases where the property name is the value of a variable, and you -rightly so- don't want to use eval).

Using variable keys to access values in JavaScript objects

The code:
function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}
The object data:
{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}
The problem:
alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".
alert(bsID); properly displays "A5A50000".
alert(data.bsID[0].time); reports "data.bsID is undefined".
alert(data[bsID][0].time); reports "data[bsID] is undefined".
I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.
You can access object properties by dot notation or by bracket notation.
var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi
When you have a dynamic value, you have to use the latter:
var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi
So what you actually want is:
alert(data[bsID][0].time);
EDIT:
Not sure what you're doing wrong, but this is working for me on Firebug's console:
var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);
In Javascript, you can use either object or array-style notation to look up an attribute. The following are equivalent:
data.A5A50000
data['A5A50000']
With the second syntax, you can use a variable in place of an object string:
data[bsID][0]
I experienced the same problem with a nested JSON API-response:
[
{
"bj_code": "2019",
"BJ_PERIODE": [
{
"nummer": 1
},
{
"nummer": 2
}
]
}
]
I could evaluate:
pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);
But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:
const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);

Categories

Resources