我列出了JSON响应,我想访问第一个"name": "Facebook, Inc."
{
"ResultSet": {
"Query": "FB",
"Result": [{
"symbol": "FB",
"name": "Facebook, Inc.",
"exch": "NAS",
"type": "S",
"exchDisp": "NASDAQ",
"typeDisp": "Equity"
}, {
"symbol": "FBIOX",
"name": "Fidelity Select Biotechnology Portfolio",
"exch": "NAS",
"type": "M",
"exchDisp": "NASDAQ",
"typeDisp": "Fund"
}, {
"symbol": "FBP",
"name": "First Bancorp",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE",
"typeDisp": "Equity"
}, {
"symbol": "FBNK",
"name": "First Connecticut Bancorp, Inc.",
"exch": "NMS",
"type": "S",
"exchDisp": "NASDAQ",
"typeDisp": "Equity"
}, {
"symbol": "FBHS",
"name": "Fortune Brands Home & Security, Inc.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE",
"typeDisp": "Equity"
}, {
"symbol": "FB2A.DE",
"name": "Facebook, Inc.",
"exch": "GER",
"type": "S",
"exchDisp": "XETRA",
"typeDisp": "Equity"
}, {
"symbol": "FBIZ",
"name": "First Business Financial Services, Inc.",
"exch": "NMS",
"type": "S",
"exchDisp": "NASDAQ",
"typeDisp": "Equity"
}, {
"symbol": "FBR",
"name": "Fibria Celulose S.A.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE",
"typeDisp": "Equity"
}, {
"symbol": "FBC",
"name": "Flagstar Bancorp Inc.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE",
"typeDisp": "Equity"
}, {
"symbol": "FFG",
"name": "FBL Financial Group Inc.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE",
"typeDisp": "Equity"
}]
}
}
我使用以下JavaScript代码来获取值:
var res = jQuery.map(data.ResultSet.Result, function (item) {
var asset = {
symbol:item.symbol,
name:item.name,
type:item.type,
exch:item.exchDisp
};
var cname=asset.name
但是我在变量cname
中得到了姓氏。如何将名字变成cname
?
答案 0 :(得分:2)
您正在获取最后一个值,因为您在map
内使用它。
在每次新cname
时创建地图新项目时,它会替换之前的cname
。
将cname
置于map
喜欢这个
var res = jQuery.map(data.ResultSet.Result, function(item) {
var asset = {
symbol: item.symbol,
name: item.name,
type: item.type,
exch: item.exchDisp
};
return asset;
});
var cname = res[0].name
答案 1 :(得分:0)
var resultArray = data.ResultSet.Result;
var cname = "";
var firstRecord = resultArray[0];
cname = firstRecord.name;
答案 2 :(得分:0)
我会像这样使用lodash的find函数:
var target = _.find(data.ResultSet.Result, function(r){
return r.name === "Facebook, Inc.";
})
这是一个jsfiddle:
https://jsfiddle.net/mckinleymedia/hxnp99vg/
这将在数组中找到第一个与return中的条件语句匹配的对象:r.name ===“Facebook,Inc。”。