выбор lodash во вложенном массиве - PullRequest
0 голосов
/ 30 апреля 2018

У меня есть массив таких объектов:

{
  "sizes":{
     "thumbnail":{
        "height":300,
        "width":300,
        "url":"http://example.com/wp-content/uploads/2017/04/web-300x300.jpg",
        "orientation":"landscape"
     },
     "medium":{
        "height":267,
        "width":400,
        "url":"http://example.com/wp-content/uploads/2017/04/web-400x267.jpg",
        "orientation":"landscape"
     },
     "large":{
        "height":441,
        "width":660,
        "url":"http://example.com/wp-content/uploads/2017/04/web-1024x684.jpg",
        "orientation":"landscape"
     },
     "full":{
        "url":"http://example.com/wp-content/uploads/2017/04/web.jpg",
        "height":1200,
        "width":1796,
        "orientation":"landscape"
     }
  },
  "mime":"image/jpeg",
  "type":"image",
  "subtype":"jpeg",
  "id":3589,
  "url":"http://example.com/wp-content/uploads/2017/04/web.jpg",
  "alt":"",
  "link":"http://example.com/web/",
  "caption":""
}

Я использую следующий фрагмент для создания нового массива только с ключами alt, caption, id и url в массиве:

images.map( ( image ) => pick( image, [ 'alt', 'caption', 'id', 'url' ] ) ),

Мой вопрос: как выбрать ключ sizes.thumbnail.url вместо корневого ключа url? Является ли это возможным? Если да, то как?

Заранее спасибо

Ответы [ 3 ]

0 голосов
/ 30 апреля 2018

Вы можете использовать обычный js,

function pickfromobject(object, key){
	var parts= key.split('.')
	if(parts.length > 1){
		var tempkey = parts.shift()
		if(!object[tempkey]){
			return null
		} else{
			return pickfromobject(object[tempkey], parts.join('.'))
		}
	} else{
		return object[parts[0]]
	}
}


function pick(arr, key){
	var result = []
	for(var i =0;i<arr.length; i++){
		result.push({[key]: pickfromobject(arr[i], key)})
	}
	return result
}

var a = [{a: {c:{d:1}}, b:2}, {a:{c:{d:3}}, b:3}]

console.log(pick(a, 'a.c.d'))
0 голосов
/ 30 апреля 2018

var array = [{
  "sizes":{
     "thumbnail":{
        "height":300,
        "width":300,
        "url":"http://example.com/wp-content/uploads/2017/04/web-300x300.jpg",
        "orientation":"landscape"
     },
     "medium":{
        "height":267,
        "width":400,
        "url":"http://example.com/wp-content/uploads/2017/04/web-400x267.jpg",
        "orientation":"landscape"
     },
     "large":{
        "height":441,
        "width":660,
        "url":"http://example.com/wp-content/uploads/2017/04/web-1024x684.jpg",
        "orientation":"landscape"
     },
     "full":{
        "url":"http://example.com/wp-content/uploads/2017/04/web.jpg",
        "height":1200,
        "width":1796,
        "orientation":"landscape"
     }
  },
  "mime":"image/jpeg",
  "type":"image",
  "subtype":"jpeg",
  "id":3589,
  "url":"http://example.com/wp-content/uploads/2017/04/web.jpg",
  "alt":"",
  "link":"http://example.com/web/",
  "caption":""
}];


var result = _.map(array, v => ({"alt":v.alt, "caption":v.caption, "id":v.id, "url":v.sizes.thumbnail.url}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
0 голосов
/ 30 апреля 2018

Создайте объект со свойством url и значением sizes.thumbnail.url, используя _.get(), и объедините его с результатами _.pick().

Примечание: Я использовал распространение объекта для объединения результатов, но вместо этого вы можете использовать Object.assign() или эквивалент lodash.

    const images = [{
    "sizes": {
        "thumbnail":
        {
            "height": 300,
            "width": 300,
            "url": "http://example.com/wp-content/uploads/2017/04/web-300x300.jpg",
            "orientation": "landscape"
        },
        "medium": {
            "height": 267,
            "width": 400,
            "url": "http://example.com/wp-content/uploads/2017/04/web-400x267.jpg",
            "orientation": "landscape"
        },
        "large": {
            "height": 441,
            "width": 660,
            "url": "http://example.com/wp-content/uploads/2017/04/web-1024x684.jpg",
            "orientation": "landscape"
        },
        "full": {
            "url": "http://example.com/wp-content/uploads/2017/04/web.jpg",
            "height": 1200,
            "width": 1796,
            "orientation": "landscape"
        }
    },
    "mime": "image/jpeg",
    "type": "image",
    "subtype": "jpeg",
    "id": 3589,
    "url": "http://example.com/wp-content/uploads/2017/04/web.jpg",
    "alt": "",
    "link": "http://example.com/web/",
    "caption": ""
}];

const result = images.map((image) => ({
  ..._.pick(image, ['alt', 'caption', 'id']),
  url: _.get(image, 'sizes.thumbnail.url')
}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
...