从对象中删除空数组

时间:2021-06-22 16:34:03

标签: javascript arrays object

我想从一个对象中删除一个数组,如果它是空的。我已经尝试过这个并且它有效,但显然它正在改变原始数据,这对我来说并不是真正的问题。我只是想知道这是否是正确的方法。

ValueOfAmount
val valueOfAmounts = dao.getAmountsWithValues().map { amountWithValue ->
    ValueOfAmount(
        amountWithValue.amount.type,
        amountWithValue.amount.amount * amountWithValue.value.value
    )
}

// Do stuff with value of amounts

2 个答案:

答案 0 :(得分:2)

也许是这样的(为了避免编辑原始数据):

const data = {
  arr1: [],
  arr2: ['ok'],
  arr3: ['ok']
}

let res = Object.entries(data).reduce((acc, el) => {
  if (el[1].length > 0) {
    acc[el[0]] = el[1]
  }
  return acc;
}, {})

console.log(res)

答案 1 :(得分:2)

你所做的是几种有效的方法之一,这是看待它的客观方式。

如果你想要一个不可变的等价物,你可以使用 filterObject.fromEntries

const data = {
    arr1: [],
    arr2: ["ok"],
    arr3: ["ok"]
};

const update = Object.fromEntries(
    [...Object.entries(data)].filter(([_, value]) => value.length !== 0)
);

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

或者只是一个很好的旧循环:

const data = {
    arr1: [],
    arr2: ["ok"],
    arr3: ["ok"]
};

const update = {};
for (const [key, value] of Object.entries(data)) {
    if (value.length) {
        update[key] = value;
    }
}

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

事实上,您可以在原始版本中使用一个很好的旧循环来修改现有对象:

const data = {
    arr1: [],
    arr2: ["ok"],
    arr3: ["ok"]
};

for (const [key, value] of Object.entries(data)) {
    if (!value.length) {
        delete data[key];
    }
}

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

甚至更旧的循环:;-)

const data = {
    arr1: [],
    arr2: ["ok"],
    arr3: ["ok"]
};

const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
for (const key in data) {
    if (hasOwn(data, key) && !data[key].length) {
        delete data[key];
    }
}

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

(在所有这些中,您可能会考虑使用 Array.isArray 守卫。)