0

There is an object below:

var obj = {“2017-12-13”: {“prop 1”: “value1”, “prop 2”: “value2”}, “2017-12-14”: {“prop 1”: “item1”, “prop 2”: “item2”}};
var arr = Object.values(obj); // Result: [{prop 1: “value1”, prop 2: “value2”}, {prop 1: “item1”, prop 2: “item2”}]

The result is incorrect because there are no " " around prop 1 and prop 2. That’s why I’m not able to get values. Do you know how to solve this problem?

How can I get values of prop 1 in a new array? (the desired result: var myArr = [value1, item1])

4
  • 6
    The quotes are a syntactic thing (and your syntax is wrong). You don't actually have a problem. Commented Dec 15, 2017 at 16:12
  • @SLaks thank you for reply. But i have the similar syntax in json file with quotes and and spaces in properties names. How should I get values in this situation? Commented Dec 15, 2017 at 16:20
  • @Olga — Load the JSON. Parse the JSON. Then it is the same. Commented Dec 15, 2017 at 16:20
  • 1
    The same way you get values from any other object. Or are you actually asking how to use bracket notation to use property names with spaces? Commented Dec 15, 2017 at 16:21

2 Answers 2

1

To process your income data I would use Array.prototype.map:

var obj = {"2017-12-13": {"prop 1": "value1", "prop 2": "value2"}, "2017-12-14": {"prop 1": "item1", "prop 2": "item2"}};

var result = Object.values(obj).map(o => o["prop 1"]); // ["value1", "item1"]

Also, on bracket notaion see MDN Property Accessors.

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

1 Comment

not sure why this has a downvote, it is the result OP expects
0

Not really sure to get your problem but I will try to answer: per instance you have this array:

var obj = {
            "2017-12-13": {"prop 1": "value1", "prop 2": "value2"}, 
            "2017-12-14": {"prop 1": "item1", "prop 2": "item2"}
           };
var arr = Object.values(obj);

If you want to get the value of the first item which points to the attribute "prop 1" you should do something like:

console.log ( arr[0]["prop 1"] );
//"value1"

Hope this answer your question.

2 Comments

Typically if you have to use a static index you're doing something wrong
@SterlingArcher I put a static index just as example since I am not sure which actually is her issue. The way she wants to loop to the items is up to her, can be used .map() as you suggest or any other methods.

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.