【问题标题】:Find a property name in an array of objects in Javascript在Javascript中的对象数组中查找属性名称
【发布时间】:2018-04-11 00:37:54
【问题描述】:

假设我们有一个数组:

var array = [
{name1: 'value1'},
{name1: 1},
{name2: 'value2'},
{name2: 2},
{name4: [{name4a: 'value4a'}, {name4b: 'value4b'}]},
{name5: [{name5a: 'value5a'}, {name5b: 'value5b'}]}
];

其中属性名称和值是随机的,但某些已知名称经常重复。我想检查数组是否有特定的属性名称(可以多于一个),用索引位置显示它,检查它有什么值。

我可以映射数组并显示正确的属性名称,但由于我是初学者,我不知道如何迭代结果...

function extractArrayPropertyName(array, property_name)
{
    return array.map(function(item)
    {
        console.log(item[property_name]);
        // I want to display only the matched names, iterate over results and check the value
    });
}

有什么想法吗?

【问题讨论】:

    标签: javascript arrays sorting object


    【解决方案1】:

    您可以使用以下方法遍历对象的键:

    for(var key in array[i])
    

    您将不得不递归搜索以找到所有嵌套键。我整理了一个可以满足您需求的快速解决方案:

    function extractArrayPropertyName(array, property_name) {
        let result = [];
        for (let i = 0; i < array.length; i++) {
            for (let key in array[i]) {
                if (Array.isArray(array[i][key]))
                    result = result.concat(extractArrayPropertyName(array[i][key], property_name));
                else if (array[i][property_name] !== undefined)
                    result.push(array[i]);
            }
        }
        return result;
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用迭代和递归方法,对元素路径的索引数组进行闭包。

      结果如下:

      [
          [0, "value1"],  // result 1 on index 0 with value 'value1'
          [1, 1]          // result 2
      ]
      

      或用于嵌套结果

      [
          [4, 0, "value4a"] // 4 and 0 are the indices.
      ]
      

      function getKeyIndex(array, key) {
          return array.reduce(function iter(path) {
              return function (r, o, i) {
                  Object.keys(o).forEach(function (k) {
                      if (k === key) {
                          r.push(path.concat([i, o[key]]));
                          return;
                      }
                      if (Array.isArray(o[k])) {
                          r = r.concat(o[k].reduce(iter(path.concat(i)), []));
                      }
                  });
                  return r;
              };
          }([]), []);
      }
      
      var array = [{ name1: 'value1' }, { name1: 1 }, { name2: 'value2' }, { name2: 2 }, { name4: [{ name4a: 'value4a' }, { name4b: 'value4b' }] }, { name5: [{ name5a: 'value5a' }, { name5b: 'value5b' }] }];
      
      console.log(getKeyIndex(array, 'name1'));
      console.log(getKeyIndex(array, 'name4a'));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多