【问题标题】:Is there a Javascript function similar to PHP's array_column?有没有类似于 PHP 的 array_column 的 Javascript 函数?
【发布时间】:2019-06-04 01:35:17
【问题描述】:

我正在使用 Vue.js

我想要的是从多维数组中得到一列名为'name'

我不确定这个多维数组的维度大小。

样本数组在这里

{
    "form":{
        "id":"123465",
        "title":"User Information",
        "fields":[
                    {
                        "type":"date",
                        "title":"Document date",
                        "name":"document_date",
                        "required":true
                    },
                    {
                        "type":"input",
                        "title":"Document no",
                        "name":"document_no",
                        "required":true
                    }
                ],
        "tabs":{
            "xxx-general":{
                "title":"General",
                "fields":[
                    {
                        "type":"date",
                        "title":"DOB",
                        "name":"dob"
                    },
                    {
                        "type":"toggle",
                        "title":"Keep my profile private",
                        "name":"is_private"
                    },
                ]
            },
            "xxx-times":{
                "title":"Ticket",
                "fields":[
                    {
                        "type":"datetime",
                        "title":"Arrival time",
                        "name":"arrival_time"
                    },
                    [
                        {"type":"number","title":"Quantity","name":"quantity"},
                        {"type":"currency","title":"Price","name":"price"}
                    ]
                ]
            }
        }
    }
}

我知道 PHP 中有 array_column 函数,我想使用与这个 PHP 函数等效的 javascript 函数。

任何人都可以帮助我

【问题讨论】:

  • 你想要的输出是什么?
  • form['fields'][0]['name'] 不起作用?
  • JS 中没有这样的原生函数,你必须遍历对象并创建一个包含所需值的数组。
  • @AntonyMN 它不是动态的 - array_column 调用看起来像 array_column(input, "name") 并且会从对象中任意数量的嵌套中提取该数据。但正如 Teemu 所说,JS 中没有内置功能。您必须滚动自定义或使用库。
  • 建立在您自己尝试的任务的基础上,您可以在stackoverflow.com/q/11922383/1169519找到

标签: javascript php vue.js


【解决方案1】:

正如其他人已经说过的,JavaScript 中没有原生解决方案(作为函数)。相反,您必须使用多个步骤。您可能想要创建一些以后可以使用的通用函数。

提示:我缩短了您的示例数据以提高可读性!

var DATA = {
    "form":{
        "id":"123465",
        "title":"User Information",
        "fields":[
                    {
                        "type":"date",
                        "title":"Document date",
                        "name":"document_date",
                        "required":true
                    },
                    {
                        "type":"input",
                        "title":"Document no",
                        "name":"document_no",
                        "required":true
                    }
                ],
        "tabs":{
            // ... shortened ...
        }
    }
}



// ====== GENERAL PURPOSE FUNCTIONS ======
function prop (path, obj) {
  return path.split('.').reduce(function (p, name) {
    return p == null ? p : p[name];
  }, obj);
}

function mapMaybe (func, arr) {
  return Array.isArray(arr) ? arr.map(func) : [];
}

function mapDeep (path, func, obj) {
  return mapMaybe(func, prop(path, obj));
}



// ====== SOLUTION ======
console.log(mapDeep('form.fields', function (x) { return x.name; }, DATA))

【讨论】:

    【解决方案2】:

    没有执行深度查找的本地方法,但实际上实现起来非常简单:

    //return an array of objects according to key, value, or key and value matching
    function getObjects(obj, key, val) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getObjects(obj[i], key, val));    
            } else 
            //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
            if (i == key && obj[i] == val || i == key && val == '') { //
                objects.push(obj);
            } else if (obj[i] == val && key == ''){
                //only add if the object is not already in the array
                if (objects.lastIndexOf(obj) == -1){
                    objects.push(obj);
                }
            }
        }
        return objects;
    }
    
    //return an array of values that match on a certain key
    function getValues(obj, key) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getValues(obj[i], key));
            } else if (i == key) {
                objects.push(obj[i]);
            }
        }
        return objects;
    }
    
    //return an array of keys that match on a certain value
    function getKeys(obj, val) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getKeys(obj[i], val));
            } else if (obj[i] == val) {
                objects.push(i);
            }
        }
        return objects;
    }
    
    
    var json = '{"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","ID":"44","str":"SGML","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}';
    
    var js = JSON.parse(json);
    
    //example of grabbing objects that match some key and value in JSON
    console.log(getObjects(js,'ID','SGML'));
    //returns 1 object where a key names ID has the value SGML
    
    //example of grabbing objects that match some key in JSON
    console.log(getObjects(js,'ID',''));
    //returns 2 objects since keys with name ID are found in 2 objects
    
    //example of grabbing obejcts that match some value in JSON
    console.log(getObjects(js,'','SGML'));
    //returns 2 object since 2 obects have keys with the value SGML
    
    //example of grabbing objects that match some key in JSON
    console.log(getObjects(js,'ID',''));
    //returns 2 objects since keys with name ID are found in 2 objects
    
    //example of grabbing values from any key passed in JSON
    console.log(getValues(js,'ID'));
    //returns array ["SGML", "44"] 
    
    //example of grabbing keys by searching via values in JSON
    console.log(getKeys(js,'SGML'));
    //returns array ["ID", "SortAs", "Acronym", "str"] 

    参考:http://techslides.com/how-to-parse-and-search-json-in-javascript

    【讨论】:

      【解决方案3】:

      只是为以前的答案添加一个解决方案:

      const data = {
        "form":{
          "id":"123465",
          "title":"User Information",
          "fields":[
            {
              "type":"date",
              "title":"Document date",
              "name":"document_date",
              "required":true
            },
            {
              "type":"input",
              "title":"Document no",
              "name":"document_no",
              "required":true
            }
          ],
          "tabs":{
            "xxx-general":{
              "title":"General",
              "fields":[
                {
                  "type":"date",
                  "title":"DOB",
                  "name":"dob"
                },
                {
                  "type":"toggle",
                  "title":"Keep my profile private",
                  "name":"is_private"
                },
              ]
            },
            "xxx-times":{
              "title":"Ticket",
              "fields":[
                {
                  "type":"datetime",
                  "title":"Arrival time",
                  "name":"arrival_time"
                },
                [
                  {"type":"number","title":"Quantity","name":"quantity"},
                  {"type":"currency","title":"Price","name":"price"}
                ]
              ]
            }
          }
        }
      };
      
      const re = /"name"\s*:\s*"(.+?)(?<!\\)"/g;
      const names = [];
      const json = JSON.stringify(data);
      let p;
      while ((p = re.exec(json)) !== null) {
        names.push(p[1]);
      }
      
      console.log(names);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-15
        • 2011-03-27
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        • 2011-10-26
        • 2021-09-17
        • 1970-01-01
        相关资源
        最近更新 更多