简体   繁体   中英

Target object value from single array

I have an array with number data and I need to target the value of the object which is inside an array.

An example to make it clear, here is the data:

[
{1: 'one'},
{2: 'two'},
{3: 'three}
]

I'm reducing it to get the one I want, so I'm left with [{3: 'three'}] . Now how to I get the 'three' string?

Many thanks

Use bracket notation

Any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number ) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

 var obj = [{ 3: 'three' }]; console.log(obj[0][3]); 

If key is unknowm:

 var obj = [{ 3: 'three' }]; console.log(obj[0][Object.keys(obj[0])]); 

You can do this, even though it's kind of messy:

var d = [{3: 'three'}];
d[0][Object.keys(d[0])[0]]

That accounts for not knowing what they key is, so any singular entry object will work.

You can simplify that a bit with another variable:

var _d = d[0];
_d[Object.keys(_d)[0]]

Though ideally you'd write a function to encapsulate this:

function firstValue(list) {
  return list[0][Object.keys(list[0])[0]];
}

Hopefully support for Object.values will clean this up:

var d = [{3: 'three'}];
Object.values(d[0])[0]

If after filtering, you're left with only one item and you don't know the key, you can access the value this way:

var obj = ([{3: 'three'}])[0];
obj[Object.keys(obj)[0]];

Hope it helps.

If your array is a = [{3: 'three'}] then use

a[0][3]

The first bracket is used for the index of the array. The second bracket is used for the key 3 of the dictionary {3: 'three'} .

If you want to have the value of the single element of the dictionary contained in the array then use

a[0][Object.keys(a[0])[0]]

But I would also add some checks on the length of the array and length of the dictionary.

I'm guessing the crux of the question is that you don't know what to put in the second bracket...

var a = {3: 'three'};
var val;
for (var i in a) val = a[i];  // val is now 'three'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM