简体   繁体   English

为数组中的每个 JavaScript 对象查找为 null 的属性

[英]Find properties that are null for every JavaScript object in an array

For example, if I have a JavaScript array of objects such as:例如,如果我有一个 JavaScript 对象数组,例如:

var jsObjects = [
   {a: 1, b: 2, c: null, d: 3, e: null}, 
   {a: 3, b: null, c: null, d: 5, e: null}, 
   {a: null, b: 6, c: null, d: 3, e: null}, 
   {a: null, b: 8, c: null, d: 1, e: null}
];

I would expect the output to be ["c", "e"].我希望输出为 ["c", "e"]。

My current solution is to call a function for each column & loop through the jsObjects:我当前的解决方案是为每列调用一个函数并循环遍历 jsObjects:

function isAllNull(col) {
    var allNulls = true;
    for (var i = 0; i < data.length; i++) {
    
       if (jsObjects[i].col != null) { 
             allNulls = false;
             break;
        }
      }
}

But I would like for this function to be more generic such that it will jsObjects with any number of arbitrary simple (ie not objects) properties.但是我希望这个函数更通用,以便它可以使用任意数量的任意简单(即非对象)属性的 jsObjects。 The objects in the array all have the same properties.数组中的对象都具有相同的属性。

If you guarantee that each object in the array has the same properties then:如果您保证数组中的每个对象都具有相同的属性,则:

  • take the keys from the first object in the array从数组中的第一个对象中获取键
  • reduce the keys and test every key in the original array for null reduce键并测试原始数组中的every键是否为null
  • if every key returns true then include the key in the output如果every键都返回 true,则在输出中包含该键

Example:例子:

 var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, b: 8, c: null, d: 1, e: null} ]; function nullCols(arr) { var keys = Object.keys(arr[0]); var nulls = keys.reduce((output, key) => { if (arr.every(item => item[key] === null)) { output.push(key); } return output; }, []); return nulls; } console.log(nullCols(jsObjects));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM