过滤或查找使用lodash查找对象然后使用嵌套数组

时间:2016-08-18 19:46:57

标签: json lodash

我有以下json

   {
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
}

我正在尝试使用lodash。我正在尝试获取值'Exterior'的url,以便使用jquery我可以连接并构建以下内容

$('wrapper').css('background-image' , 'url('+url+')')

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用findget的组合来获取网址:

var obj = _.find(json.records, function(el) {
  return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');



var json = {
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
};

var obj = _.find(json.records, function(el) {
  return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');

console.log(url);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
&#13;
&#13;
&#13;