Acessing an object propery with array bracket notation - javascript

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

Related

Can I change a JSON key from string value to an array of value in JS

Hi I would like to check if there's a way to convert one of my JSON property's value from string to an array of string.
What I have:
const testJSON = {
"name": "Albert"
}
What I want:
const testJSON = {
"name": ["Albert"]
}
Many thanks for any help and direction I could explore!
You can give a try to this dynamic solution with the help of Object.keys() and Array.forEach() method.
const testJSON = {
"name": "Albert"
};
Object.keys(testJSON).forEach(key => {
testJSON[key] = [testJSON[key]]
});
console.log(testJSON);
You can assign new value which can be string or array to json property.
For example:
const testJSON = {
"name": "Albert"
}
// new array which we will assign to previous array property
const newArray = ["Albert", "John"];
// assigning new array to old json property
testJSON.name = newArray;
Don't think so, you only do maybe like the comment above
{name: [testJSON.name]}
if you have array, u can do .map for it

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'

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

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