Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concatenate (variable + object key names) to get the object values in dot notation [duplicate]

Assuming I've a JSON object like this:

var myObj = {
    'question1': {
        'option1': 'foo',
        'option2': 'bar',
        'option3': 'baz'
    },
    'question2': {
        ...
    },
    'question3': {
        ...
    }
};

And since its children always has a number in its keys, I want to do a loop and concatenate the loop's index to the object keys, and get the values in the dot notation method...

So, I guess to get the values, I need to do some thing like this:

myObj.'question'+i

How can I do the concatenation right?

like image 655
Homer Avatar asked Nov 12 '16 15:11

Homer


People also ask

How do I concatenate values in a column in a table?

To start, you may use this template to concatenate your column values (for strings only): df ['New Column Name'] = df ['1st Column Name'] + df ['2nd Column Name'] + ... Notice that the plus symbol (‘+’) is used to perform the concatenation.

How to access an object value using a variable key?

We know that an object value can be accessed by using a Dot notation or Bracket notation. But we can also access the value using a variable key. Let's look over them in a nutshell. In the following example, object value is accessed using Dot and Bracket notation. Using a bracket notation is nothing but using a string key.

How to concatenate column values in Python using PANDAS?

In this guide, I’ll show you how to concatenate column values in Python using pandas. To start, here is a template that you may use to concatenate column values in Python: df1 = df ['1st Column Name'] + df ['2nd Column Name'] + ... Notice that the plus symbol (‘+’) is used to perform the concatenation.

What does the plus symbol mean in concatenation?

Notice that the plus symbol (‘+’) is used to perform the concatenation. Also note that if your data-set contains numbers, and you are trying to use the above template, you’ll get this error: ‘TypeError: ufunc ‘add’ did not contain a loop with signature matching types dtype (‘<U32’) dtype (‘<U32’) dtype (‘<U32′)’


1 Answers

Simply do

myObj['question'+i]

This is because the dot operator would not accept string with it as per javascript. So you will have to use square brackets instead which is often used to access properties of an object dynamically.

like image 168
Rahul Arora Avatar answered Nov 14 '22 22:11

Rahul Arora