获取具有数组内部对象所有键的数组

时间:2018-08-14 07:02:42

标签: javascript jquery arrays node.js ecmascript-6

我停留在要递归遍历数组中所有对象并获取数组数据结构中这些对象的键的位置。我知道如何循环获取对象的键。但是这里的问题是我需要递归地使用柔性对象。灵活的意思是它可以具有任何级别的嵌套属性。

所以,我有一个像这样的数组:

let record = [{
    "province": "string",
    "city": "string",
    "type": "alternative_address",
    "address_line1": "string",
    "post_code": "5858"
  },
  {
    "province": "string",
    "city": "string",
    "type": "alternative_address",
    "post_code": "5858",
    "embedeer": {
      "veryEmbedded": {
        "veryveryEmbeded": 'yes'
      }
    }
  }
];

通过一些计算,我期望输出如下:

['province','city','type','address_line1','post_code','embedeer', 'embedeer.veryEmbedded', 'embedeer.veryEmbedded.veryveryEmbeded'];

我为此付出了很多努力,我在数组上使用了reduce()操作,但是我无法做到这一点。

4 个答案:

答案 0 :(得分:2)

您需要编写一个具有2个输入的递归函数

  • 对象
  • 前缀(未为第一级键定义)

let record = [{"province":"string","city":"string","type":"alternative_address","address_line1":"string","post_code":"5858"},{"province":"string","city":"string","type":"alternative_address","post_code":"5858","embedeer":{"veryEmbedded":{"veryveryEmbeded":"yes"}}}];

function addKeysToSet(o, p) {
  Object.keys(o).forEach(k => {
    let key = p ? p + "." + k : k; // Create the key hierarchy
    keys.add(key); // Add key to the set 
    // If the value is an object, call the function recursively 
    if(typeof o[k] === 'object') {
      addKeysToSet(o[k], key);
    }
  });
}

let keys = new Set(); // Create set of unique keys
// For each object in array, call function that adds keys to the set
record.forEach(o => addKeysToSet(o));
let result = Array.from(keys); // Create array from set
console.log(result); // logs result

答案 1 :(得分:1)

您可以采用迭代和递归的方法,并使用Set的功能来获取唯一值。

function iter(object, keys) {
    return Object
        .entries(object)
        .reduce((r, [k, v]) => r.concat(keys.concat(k).join('.'), v && typeof v === 'object'
            ? iter(v, keys.concat(k))
            : []
        ), []);        
}

var record = [{ province: "string", city: "string", type: "alternative_address", address_line1: "string", post_code: "5858" }, { province: "string", city: "string", type: "alternative_address", post_code: "5858", embedeer: { veryEmbedded: { veryveryEmbeded: 'yes' } } }],
    keys = [...record.reduce((s, o) => iter(o, []).reduce((t, v) => t.add(v), s), new Set)];

console.log(keys);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以展平对象,然后获取关键点。

// form https://gist.github.com/penguinboy/762197

let record = [{"province":"string","city":"string","type":"alternative_address","address_line1":"string","post_code":"5858"},{"province":"string","city":"string","type":"alternative_address","post_code":"5858","embedeer":{"veryEmbedded":{"veryveryEmbeded":"yes"}}}];

var flattenObject = function(a) {
  var b = {};
  for (var c in a)
    if (a.hasOwnProperty(c))
      if ("object" == typeof a[c]) {
        var d = flattenObject(a[c]);
        for (var e in d) d.hasOwnProperty(e) && (b[c + "." + e] = d[e]);
      } else b[c] = a[c];
  return b;
};

console.log(flattenObject(record) )

/*
 It is also taking care of index numbers of the array. ("0.province" instead of "province" If multiple entries are passed)  
 
 */
console.info( "All keys", Object.keys(flattenObject(record) ) )

// Simple
console.info( "keys", Object.keys(flattenObject(record[1]) ) )

答案 3 :(得分:0)

var record1 = [{"province": "string","city": "string","type": "alternative_address","address_line1": "string","post_code": "5858" },
  { "province": "string","city": "string",
    "type": "alternative_address",
    "post_code": "5858",
    "embedeer": {
      "veryEmbedded": {
        "veryveryEmbeded": 'yes'
      }
    }
  }
];

var output = [];
function getAllKeys(obj,precedor="") {
  var temp = Object.entries(obj);
  temp.forEach((el) => 
               typeof el[1] == "object" ? ( output.push(el[0]),getAllKeys(el[1],precedor==""? el[0]: precedor+"."+el[0])): output.push(precedor==""? el[0]: precedor+"."+el[0]));
}
 record1.forEach((el,i) => getAllKeys(el,""));
//To avoid duplicate entries convert array to object.
console.log(...(new Set(output)));