JavaScript return 对象数组中全为空的键数组

JavaScript return array of keys that are all empty in array of objects

我有一个对象数组

const arrayOfObjects = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}];

我需要 return 数组中所有对象中的空键数组。所以对于上面的例子,它会 return ['firstKey', 'fourthKey'] 而不是 'secondKey',因为它只有一个对象是空的。

我发现了很多 return 布尔值的示例(如下所示),但无法找到 return 实际空键的方法。谢谢

const isEmpty = Object.values(object).every(x => (x === ''));

Array.prototype.every returns true when every item satisfies the predicate you pass as a callback. What you actually need is Array.prototype.filter:

const arrayOfObjects = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}];

const deduplicate = arr => [...new Set(arr)];

const isEmpty = arrayOfObjects.flatMap(x => Object.entries(x)).filter(([, value]) => !value).map(([key]) => key);

const uniqueIsEmpty = deduplicate(isEmpty);

console.log(uniqueIsEmpty);

const arrayOfObjects = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}];
let k = []
arrayOfObjects.map(obj => { k = k.concat(k, Object.keys(obj))})
let arr = [...new Set(k)];
console.log(arr);
  

从数组中的第一个对象中获取键,然后通过检查所有对象中每个键是否为空来过滤它们 Array.every():

const checkAllEmpty = arr =>
  Object.keys(arr[0] ?? {}) // get the keys from the 1st object or use an empty object as fallback
    .filter(key => arr.every(o => o[key] === '')) // filter the keys by checking each object in the array

const arr = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}]

const result = checkAllEmpty(arr)

console.log(result)

旧答案:

将array缩减为Map,统计key为空的次数。使用 Array.from() 将 Map 转换为 [key, value] 的数组,过滤所有值小于数组长度的条目,并映射到键数组:

const arr = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}]

const result = Array.from(arr.reduce((acc, obj) => {
    Object.entries(obj)
      .forEach(([k, v]) => {
        if (v === '') acc.set(k, (acc.get(k) ?? 0) + 1)
      })

    return acc
  }, new Map))
  .filter(([, v]) => v === arr.length)
  .map(([k]) => k)

console.log(result)

此版本将假设未定义的键也为“空”,以防数组中的对象具有不一致的键。

const arr = [
    {firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''}, 
    {firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}
];

const isEmpty = v => v == '';

const result = Array.from(
    arr.reduce((acc, obj) => 
        Object.entries(obj).reduce((_, [k, v]) => 
            acc.set(k, acc.has(k) ? acc.get(k) && isEmpty(v) : isEmpty(v))
        , null)
    , new Map())
).filter(([, v]) => v).map(([k]) => k);

console.log(result)