我有以下JSON并将其读取为-
this.state = {filterAttributes: MYResult.ParametricList_Filter_Attributes || []}
{
"ParametricList_Attributes": [
....
....
....
],
"ParametricList_Filter_Attributes": [
{
"PartNumber": "Part Number",
"ProductLine": "Product Line"
}
],
"Products": [
....
....
....
]
}
现在,我希望有一个常量,其中将包含“ ParametricList_Filter_Attributes”的所有值。
在下面的代码中,我在“ attr”中得到的是[object, object]
。如何仅获取数组或列表形式的值?
const filterAttrs = this.state.filterAttributes.map(attr => {
console.log("attr --"+attr)
});
答案 0 :(得分:3)
在下面的代码中,我在“ attr”中得到的是
[object, object]
。
仅在将其转换为字符串时(如在该代码中所做的那样)。这是一个对象。
如何只获取数组形式的值?
如果您只需要值,请使用Object.values
。
const filterAttrs = this.state.filterAttributes.map(attr => {
console.log(Object.values(attr)); // ["Part Number", "Product Line"]
});
实时示例:
const data = {
"ParametricList_Attributes": [
/*
....
....
....
*/
],
"ParametricList_Filter_Attributes": [
{
"PartNumber": "Part Number",
"ProductLine": "Product Line"
}
],
"Products": [
/*
....
....
....
*/
]
};
const filterAttrs = data.ParametricList_Filter_Attributes.map(attr => {
console.log(Object.values(attr)); // ["Part Number", "Product Line"]
});
如果需要属性键和值,请使用Object.entries
,它为您提供键和值作为数组:
const filterAttrs = this.state.filterAttributes.map(attr => {
console.log(Object.entries(attr)); // [["PartNumber", "Part Number"], ["ProductLine", "Product Line"]]
});
实时示例:
const data = {
"ParametricList_Attributes": [
/*
....
....
....
*/
],
"ParametricList_Filter_Attributes": [
{
"PartNumber": "Part Number",
"ProductLine": "Product Line"
}
],
"Products": [
/*
....
....
....
*/
]
};
const filterAttrs = data.ParametricList_Filter_Attributes.map(attr => {
console.log(Object.entries(attr)); // [["PartNumber", "Part Number"], ["ProductLine", "Product Line"]]
});