我有以下javascript
{
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"
[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1},
{\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
我想做的是使用javascript
从TagName
部分获得Tags
当我使用JSON.parse(Obj.Tags);
时,我会在Tags
部分得到所有我只想要TagName
的地方
有可能吗?
答案 0 :(得分:3)
有可能。您可以使用.map
函数。
var tagNames = obj.Tags.map(function(x){
return x.TagName;
});
var obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":
[{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}]
};
var tagNames = obj.Tags.map(function(x){
return x.TagName;
})
console.log(tagNames)
答案 1 :(得分:1)
我想我可能知道您的问题是什么。
您是否希望您的标签仅是TagName的数组?
下面是示例代码:
var Obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
// Get Tags data to array object
var Tags = JSON.parse(Obj.Tags);
// Get simple array of TagNames
var TagNames = Tags.map(x=>x.TagName);
console.log(TagNames);
// Get array of objects with only TagName key value pair
var TagNamesFormat2 = Tags.map(function(x){
return {"TagName" : x.TagName}
});
console.log(TagNamesFormat2);
答案 2 :(得分:0)
您可以在标记
上使用map()
// Parsed object
var data = {
"Exists": true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,
"Fav":false,
"Shield":false,
"Tags": [
{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}
]
}
console.log(data.Tags.map(tag => tag.TagName));
答案 3 :(得分:0)
尝试tags.map(a => a.TagName);
var myObj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
};
var tags = JSON.parse(myObj.Tags);
var tagNames = tags.map(a => a.TagName);
console.log(tagNames);