javascript access multidimensional object not working - javascript

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

Related

Acessing an object propery with array bracket notation

I want to access a specific property in an object. Using an array for example
let array = ["tom","tony", "jerry"];
let object = {
tony: "Brother",
tom: "Uncle",
jerry: "Cousin",
};
object.array[1];
I'm trying to access object.tony but what happens is that it returns object."tony" instead.
The problem is that it returns it as a string so it causes an error.
Is it possible to return array[1] not as a string?
In object.array[1], JS will think your looking for array inside object, which does not exist. If an array was in the object, it would work:
let object = {
array: ["tom", "tony", "jerry"],
// some other stuff...
};
console.log(object.array[1]);
You can use brackets instead:
object[array[1]];
Example:
let array = ["tom","tony", "jerry"];
let object = { tony: "Brother", tom: "Uncle", jerry: "Cousin", };
console.log(object[array[1]]);

How to convert data to string

I have data for example like this:
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}]
And I want to convert them into like this:
data: ['Apple','Microsoft','Google']
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
One way is to use Array.map and replace the object ele.tag with just the value return ele.tag:
var data =
[{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
data = data.map(function(ele){ return ele.tag; });
console.log(data);
Or in ES6 you can simply this even more:
data = data.map(ele => ele.tag);
You could use a for-in loop and push the attribute of the object into an array.
var data = [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
var tags = [];
for (prop in data) {
tags.push(data[prop].tag);
}
console.log(tags);
For easier handling let's take the object in the OP's code and assign it to a variable, as follows:
var obj = {"data":[{"tag":'Apple'},{"tag":'Microsoft'},{"tag":'Google'}]};
var {data}= obj; // object destructing ...
var mapped = data.map(function( e ){ return e.tag});
// re-assigning value of object's data property
obj["data"] = mapped;
console.log(obj); // obj.data now pertains to array of strings
The problem described by the OP involves an object whose data property refers to an array of objects, each with a tag property. The OP inquires as to how to revise the data property so that it refers instead to an array of string values corresponding to each object's tag property.
This example makes use of destructuring to access the array of objects. Then, it uses the array's map() method to access every element's tag property and thereby obtain its string value. The beauty of map() is that it performs iteration behind the scenes sparing the user from having to hand-code a loop with the correct logic -- although in functional programming languages instead of using iteration, recursion is more apt to be utilized for this purpose. Finally, the value of the object's data property is reset to contain the specified array of strings.

Output value from Json Array

I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;

Javascript how to push item into array that is stored in object

So I have an object:
var subDataMap = {count: 0, data: []};
And I tried insert a new empty array object into the data array stored in subDataMap:
subDataMap.data.push(new Array());
However it is not working as Javascript thinks push is a nested property inside subDataMap. As the error I get is
Uncaught TypeError: Cannot read property 'push' of undefined
Suppose You have an Array like this:
var obj = {
arrayOne: []
};
You can do like this:
var arrayLetters = ['x', 'y'];
obj.arrayOne.push(arrayLetters);

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