You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套数组中使用Lodash的pick方法提取指定属性?

嘿,我来帮你搞定这个Lodash提取属性的问题~首先先提个小细节:你给出的结构其实是嵌套对象(不是对象数组哦),不过这不影响我们用Lodash的pick来灵活处理,分几种常见场景给你演示:

场景1:提取所有尺寸对象里的指定属性

比如你想让每个尺寸只保留url和width,可以结合_.mapValues和_.pick来做——mapValues负责遍历sizes下的每个尺寸对象,pick负责筛选每个对象里的目标属性:

const _ = require('lodash');

const imageData = {
  "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"
    }
  }
};

// 提取每个尺寸里的url和width属性
const result = _.mapValues(imageData.sizes, size => _.pick(size, ['url', 'width']));
console.log(result);

运行后会得到一个和原sizes结构一致,但每个子对象只保留url和width的新对象。

场景2:提取特定尺寸的全部属性

如果你只想保留sizes里的thumbnail和large这两个尺寸的所有属性,直接对sizes对象用_.pick就行:

const result = _.pick(imageData.sizes, ['thumbnail', 'large']);
console.log(result);

这时候返回的对象就只有thumbnail和large两个键,每个键对应的原属性都会完整保留。

场景3:提取特定尺寸的指定属性

如果既要选某几个尺寸,又要限制这些尺寸里的属性,就把上面两种方法组合起来:

// 先筛选出thumbnail和large尺寸,再给这两个尺寸只保留url和height
const result = _.mapValues(
  _.pick(imageData.sizes, ['thumbnail', 'large']),
  size => _.pick(size, ['url', 'height'])
);
console.log(result);

这样得到的就是只包含thumbnail和large,且每个里面只有url和height的精简对象。

额外小技巧:如果是真的对象数组怎么办?

假设你有一个包含多个图片结构的对象数组,那把_.mapValues换成_.map就行,比如:

const imagesArray = [imageData, imageData]; // 模拟对象数组
const result = _.map(imagesArray, img => 
  _.mapValues(img.sizes, size => _.pick(size, ['url', 'width']))
);

内容的提问来源于stack exchange,提问作者leemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:42:12