Lodash 查找对象数组

Lodash find for Array of objects

我有以下 JsonArray:

arr = [
      {
        "name": "test",
        "alias": "alias1",
        "type": 1
      },
      {
        "name": "test",
        "type": 0
      },
      {
        "name": "abc",
        "alias": "alias2",
        "type": 1
      }
    ]

并且我想使用变量值(可能包含别名/键)查找。所以基本上 find 的 首选应该是别名,如果没有找到具有相同值的别名那么它应该在 "name" 中搜索并且 "alias" 不存在 .

通常它会像这样:

_.find(arr, {
 alias: value 
})

但是如果找不到 alias=value,我希望代码 return 我的 obj where name = value

1) 例如:值 = "alias1" 预期==>

{
    "name": "test",
    "alias": "alias1",
    "type": 1
  }

2) 例如:值 = "test" 预期==>

{
        "name": "test",
        "type": 0
      }

您需要采用自定义回调,它采用两个可能的属性来检查值。

function find(array, value) {
    return _.find(array, o => o.alias === value || o.name === value)
}

var array = [{ name: "abc", alias: "abc_alias", type: 1 }, { name: "tofind", type: 2 }, { name: "def", alias: "al1", type: 3 }];

console.log(find(array, 'abc_alias'));
console.log(find(array, 'tofind'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js">

您需要使用查找(_.find()Array.find())来查找 alias 匹配项,如果找到 none,请再次使用查找来查找name 匹配:

const findAliasOrName = (value, arr) =>
  _.find(arr, { alias: value }) || _.find(arr, { name: value });

const arr = [{"name":"test","type":0},{"name":"test","alias":"alias1","type":1},{"name":"abc","alias":"alias2","type":1}]

console.log(findAliasOrName('alias1', arr));
console.log(findAliasOrName('test', arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

您可以按如下方式进行:

如果 alias 键在 obj 中可用,则将值与 alias 匹配,否则将值与 name 匹配 键使用 三元运算符

var arr = [
      {
        "name": "test",
        "alias": "alias1",
        "type": 1
      },
      {
        "name": "test",
        "type": 0
      },
      {
        "name": "abc",
        "alias": "alias2",
        "type": 1
      }
    ];

const findValue = (arr, value) => {
    return _.find(arr, (elem) => {
        return elem.alias ? elem.alias === value : elem.name === value;
    });
}

console.log(findValue(arr, 'alias1'));
console.log(findValue(arr, 'test'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>