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?
答案 0 :(得分:3)
您可以通过Object.values
和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)))
您还可以递归地获取如下值:
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))