0

I have a javascript object like the following:

var Numeric_values = {
US:  {01: "202-555-0151", 02: "202-555-0167", 03: "202-555-0150"},
CAD: {01: "613-555-0144", 02: "613-555-0192", 03:"613-555-0151"},
AUS: {01: "1900 654 321"}
};

I am attempting to access all of the values of this object and listing them out as a string like this:

"202-555-0151","202-555-0167", "202-555-0150"
"613-555-0144", "613-555-0192","613-555-0151"
"1900 654 321"

I have so far attempted to use Object.values(Numeric_Values) and

for (let key in Numeric_values){
      console.log(Numeric_values[key]);
  }

and these always return as [object,object], how can i fix this?

2
  • 2
    And how is textOut() defined? That's what you should have showed in your attempt. Commented Nov 16, 2018 at 21:48
  • Sorry, i edited it out. For the purpose of this it functionally works as console.log(). Commented Nov 16, 2018 at 21:56

1 Answer 1

3

You can print/access them via Object.values and Array.forEach:

var data = {
  US: {
    01: "202-555-0151",
    02: "202-555-0167",
    03: "202-555-0150"
  },
  CAD: {
    01: "613-555-0144",
    02: "613-555-0192",
    03: "613-555-0151"
  },
  AUS: {
    01: "1900 654 321"
  }
};

Object.values(data).forEach(x => console.log(...Object.values(x)))

You could also recursively get the values like so:

var data = {
  US: {
    01: "202-555-0151",
    02: "202-555-0167",
    03: "202-555-0150"
  },
  CAD: {
    01: "613-555-0144",
    02: "613-555-0192",
    03: "613-555-0151"
  },
  AUS: {
    01: "1900 654 321"
  }
};

const flatten = (obj, a = []) => Object.values(obj)
  .reduce((r, c) => (typeof c == 'object' ? flatten(c, a) : r.push(c), r), a)

console.log(...flatten(data))

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

4 Comments

Thanks a lot! that is exactly what i needed, how does .map work differently from what i have been doing though?
You don't need map since you don't intend to create a new array. forEach is more appropriate.
You can use forEach
forEach it is. Thanks.

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.