Javascript object is in array but can't access it - javascript

I have a for loop which iterates through currentObject in response.
This code:
console.log(response[currentObject]);
Clearly shows that response[currentObject] has among other properties, "start".
However, this code tells me the variable is undefined:
console.log(response[currentObject].start);
Why is this? Note that "start" is a date variable.
Here is the whole function:
function(response) {
for (var currentObject in response) {
//Parsing the data before its used
//"17\/10\/2012 20:55:00"
var phpStartDate = response[currentObject].start;
console.log(response[currentObject]);
var phpStopDate = response[currentObject].stop;
var datePartsStart = phpStartDate.match(/(\d+)/g);
var datePartsStop = phpStopDate.match(/(\d+)/g);
var parsedDateStart = new Date(datePartsStart[2], datePartsStart[1], datePartsStart[0], datePartsStart[3], datePartsStart[4], datePartsStart[5]);
var parsedDateStop = new Date(datePartsStop[2], datePartsStop[1], datePartsStop[0], datePartsStop[3], datePartsStop[4], datePartsStop[5]);
response[currentObject].start = parsedDateStart;
response[currentObject].stop = parsedDateStop;
//debugger;
};
return response;
}
Forgot to add, I'm using jQuery 1.8.2, which I believe handles dates differently than 1.7 (but I can't use 1.7 because I had a whole bunch of other problems with it!)
Here is the output of console.log(response):Object
data: Array[3]
0: Object
hourly: "4.00"
id: "40"
staff: "James Hadley"
start: "2012-09-25 00:00:00"
stop: "2012-09-27 00:00:00"
__proto__: Object
1: Object
hourly: "25.00"
id: "39"
staff: "James Hadley"
start: "2012-10-17 21:12:00"
stop: "2012-10-26 02:30:00"
__proto__: Object
2: Object
length: 3
__proto__: Array[0]
total: 3
__proto__: Object

I guess it's a timing issue, because the console.log object is live. Try
console.log(JSON.stringify(response[currentObject]));
I bet it does NOT include start even thought without stringify it does. Your response is asynchronous and you access start too early (your code doesn't show that part).
Now with your comment it's obvious. It's an array and you are missing and index, e.g. 0.
console.log(response[currentObject][0].start);

use
currentObject.start = parsedDateStart
instead of
response[currentObject].start = parsedDateStart

Related

How to iterate through array of objects and stringify

I've been at this for a bit trying to come up with a solution. I have tested a handful of stack solutions to iterate through nested objects but haven't gotten this to work correctly. My data structure is below.
I've been trying to first off iterate through nested objects which this stack seemed to be similar to mine.
Iterate through Nested JavaScript Objects
However, when I'm in my for loop getting access to geo, value object to grab all of its properties, ip, hostname, city etc I'm coming up empty handed with undefined. Here's a code snippet of what I've tried below.
I'm trying to take all of the keys and values in this entire object and stringify them into a beautiful parameter string to send over to the server in an ajax request.
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
o.value.ip;
}
}
0: {name: "firstname", value: "John"}
1: {name: "lastname", value: "Smith"}
2: {name: "email", value: "asddas#gmail.com"}
3: {name: "password", value: "asdsdadasads"}
4: {name: "paypal_email", value: "asdsa#gmail.com"}
5: {name: "phone", value: "1234567894"}
6: {name: "geo",value: "
{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
__proto__: Object
length: 7
__proto__: Array(0)
The problem is that the structure of the geo object is odd:
name: "geo",value: "{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
The value looks to be a string in JSON notation. You'll have to parse it first in order to look up properties on it:
if (o.name === "geo") {
const nestedObj = JSON.parse(o.value);
console.log(nestedObj.ip);
}
You might also consider fixing whatever's serving you that object so that the value is an actual object - if that's possible (it may not be, but it would make the code make a lot more sense).
You can also consider using .find instead of a for loop, to make the code shorter and more elegant:
const json = myarray.find(({ name }) => name === 'geo').value;
const nestedObj = JSON.parse(json);
(if the geo object may not exist, test for undefined first, of course)
It would appear that the value field for the object with the name of "geo" is a JSON string.
Because the value is a string, you won't be able to directly access the ip field without first parsing that string to an object:
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
/* "Convert" the JSON string in o.value to the corresponding object */
const valueObject = JSON.parse(o.value);
/* The ip field can now be accessed from the valueObject, parsed from
the JSON string in o.value */
console.log(valueObject.ip);
}
}

How to access of a array with objects if i dont know the array key/index?

I have an array, inside this I have objects. I need to work with this and need to access to the object data.
Here is a sample of this array:
var result <-
(16)array […]
​
0:object {…}"myobjectname1": {…} style_name: "border-top-right-radius"
​​​ style_unit: "px"
​​​ style_value: "0"
​​​
1:object {…}"myobjectname2": {…} style_name: "border-bottom-right-radius"
​​​ style_unit: "px"
​​​ style_value: "0"
​​​
2:object { "myobjectname3": {…} }
​
3:object { "myobjectname4": {…} }
​
4:object { "myobjectname5": {…} }
...
I want to access directly to the different objects by the objectname
Example alert("result.myobjectname1.style_name");
It seem that this could not work, because I don't access the array by the index in this case [0]!?
I don't know this index, it could be different every time.
Is there a way, to directly access the objects by the objectname or in which way, I have to create a array/object that it works?
In php I will do it with a simple array, in JavaScript its not possible because my index is alphanumeric.
UPDATE
This is the way i create the datas in a each-loop
var match=new Array();
each(...)
{
...
var r = null;
r={ [myobjectname_from_variable] : { 'style_name': res_stylename,
'style_value': res_stylevalue,
'style_unit' : elem_styleunit} };
match.push(r);
...
}
Important: The value of myobjectname_from_variable is the same as res_stylename and it contains something like "border-top-right-radius"
Here we have to think about, how i can call this in javascript. For example
object.border-top-right-radius.style_value
wont breack and returns a error of undefined "right"...
You could build an object with all objects of the array. Then take the key of the wanted object for access.
var array = [
{ foo: { id: 1, name: 'foo' } },
{ bar: { id: 2, name: 'bar' } },
{ baz: { id: 3, name: 'baz' } }
],
object = Object.assign(...array);
console.log(object.foo.id);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For a faster access via a key, you could build your object with a defined object, like
var data = {};
And in the loop, you could assign the value object like this with a property accessor
// inside of the loop
data[myobjectname_from_variable] = {
style_name: res_stylename,
style_value: res_stylevalue,
style_unit: elem_styleunit
};
Your best bet is to iterate the array and then call the index of each iteration. There's also an array method called .forEach that wraps this up for you.
var yourArray = []; // contains the array of objects you mentioned
yourArray.forEach(object => {
const key = Object.keys(object)[0];
alert(object[key].style_name);
})
Update
Your main issue is the use of hyphens in your keys. If you want to index an object like that then you'll need to reference the keys as strings.
const obj = {'border-top-right-radius':'style_value'};
const test = obj['border-top-right-radius'];
console.log(test); // this logs 'style_value '
const other = obj.border-top-right-radius;
// This will throw that 'right' is undefined.
If you want that format then change your hyphens to underscores. With underscores, there's no issue directly referencing them as you desire. You can easily remap to the hyphenated string later for what you're doing with .replace
const underscoreReplacement = 'border_top_right_radius';
const actualSheetValue = underscoreReplacementreplace(/_/g, '-');
console.log(actualSheetValue); // logs 'border-top-right-radius'

javascript access multidimensional object not working

I have an object:
var Obj = [{
id: "",
position: {
cartesian: [],
polar: [],
bob: "INERTIAL"
}
}];
When I go to set obt.id
Obj.id="sam/reconnaissance - "+samName;
It works fine.
However when I go to access Obj.position.cartesian
(Obj.position.cartesian).push(fooBar[i][t][p]);
I get this error:
(Obj.position.cartesian).push(fooBar[i][t][p]);
^
TypeError: Cannot read property 'cartesian' of undefined
Why? I have tried Obj['position']['cartesian'] and still nothing
What am I doing wrong?
Obj is not an object, it is an Array so you have to access first element with index 0. Try it like
Obj[0]['position']['cartesian']
You aren't using an object, you are using an array.
An object looks like this:
var obj = {
id: 0
};
What you have is an object within an array: (note [)
var obj = [{id: 0}];
Obj is an array with single element as object, hence to access position you can use any of these syntax
Obj[0]['position']['cartesian']
Obj[0].position.cartesian
Again cartesian is an array hence to call push you can use
Obj[0]['position']['cartesian'].push(foobar[i][t][p])
Obj[0].position.cartesian.push(foobar[i][t][p])

how to create JavaScript object using a for loop?

i have an object sample data:
[Object, Object, Object]
0: Object
test_id: "1"
area: "high"
1: Object
test_id: "1"
area: "saw"
2: Object
test_id: "2"
area: "look"
i am trying to create a new object by grouping by test_id.
var obj = new Object();
$.each(data, function(k, v){
obj[v.test_id] += {area: v.area};
});
this doesn't seem to work, it returns only one object line...
i am trying to get something like:
1: {
{area: "high"}
{area: "saw"}
}
2: {
{area: "look""
}
any ideas? thanks
After your edit I notice something, you're trying to create a javascript object with a property with no name, this is not the format. In JSON (javascript object notation) each property must have a value, what you are trying to store better fits an array.
Instead, push it into an array
$.each(data, function(k, v){
obj[v.test_id].area.push(v.area);
});
just remember to create obj[v.test_id] first and to set its area property to [].
This results in:
1: {
area: ["high","saw"]
}
3: {
area: ["look"]
}
Also, if you're willing to consider using underscore it has very powerful (yet basic) collection methods, you might want to have a look at http://underscorejs.org/#groupBy

Confuse about array and object in node.js

I have a array for store object, which have an object in it already:
var obj = [{
name: 'json',
lang: 'en'
}];
console,.log(obj) //the result is OK;
then I want push another object into it, just like:
var newObj = {
name: 'lee',
lang: 'zh'
}
obj.push(newObj)
but after this I print the obj array,console.log(obj), the result is 2 !!
Why this happen? How can I solve this problem?To store object in array correctly
Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).

Categories

Resources