0

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

1
  • "target" means read or write or both? Commented Sep 29, 2016 at 18:06

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

This presumes you know that the key is 3.
@Kreitzo – What is input object ?
1

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.

Comments

1

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]

Comments

0

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'

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.