如何使用 Lodash 从具有对象数组的对象中选取密钥?

问题描述 投票:0回答:3

我想过滤服务器响应数据的对象。 我的对象包含在对象数组中。

const object1 = {
    _id: '12345',
    publicId: 'object-1',
    arrayOfObject2: [
        {
            _id: '12345',
            publicId: 'object-2',
            username: 'allen',
            password: '123456',
        },
    ],
};

例如,我想从

publicId
中选择
object1
,并从每个
username
中选择
object2

我尝试了这个,但这不起作用:

const pickedObject = lodash.pick(object1, ['publicId', 'arrayOfObject2.username']);
javascript node.js arrays object lodash
3个回答
0
投票

为此你不需要 Lodash。

const myObject = {
    ...object1,
    usernames: object1.arrayOfObject2.map(
        ({ username }) => username
    ),
};

0
投票

要访问对象属性,您可以借助

dot(.)
表示法来实现。例如:
object.key

但是如果您想从对象数组中访问每个对象属性值。在这种情况下,您必须借助

Array.map()
方法进行迭代。

现场演示

const object1 = {
    _id: '12345',
    publicId: 'object-1',
    arrayOfObject2: [
        {
            _id: '12345',
            publicId: 'object-2',
            username: 'allen',
            password: '123456',
        },
    ],
};

const res = object1.arrayOfObject2.map(({ username }) => username);

console.log(object1.publicId); // prints 'object-1' 
console.log(res); // prints ['allen']

更新:查看作者对另一个答案的评论后,顶级对象也是对象数组的一部分。因此,您也可以使用 lodash

._map
方法进行迭代。

现场演示

const arr = [{
  _id: '12345',
  publicId: 'object-1',
  arrayOfObject2: [
    {
      _id: '12345',
      publicId: 'object-2',
      username: 'allen',
      password: '123456',
    }
  ]
}];

const res = _.map(arr, (obj) => {
  return {
    publicId: obj.publicId,
    arrayOfObject2: _.map(obj.arrayOfObject2, (obj2) => {
     return {
        username: obj2.username
     }
    })
  }
});

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


0
投票

您可以使用 lodash 文档中的

mapValues
函数 https://lodash.com/docs/4.17.15#mapValues

var users = {
  'fred':    { 'user': 'fred',    'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
};

_.mapValues(users, function(o) { return o.age; });
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)

// The `_.property` iteratee shorthand.
_.mapValues(users, 'age');
// => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
© www.soinside.com 2019 - 2024. All rights reserved.