我正在尝试找到一种创建对象的方法,在创建时它会忽略未定义的值。
在下面的示例中,变量someNames在创建对象时具有未知内容。
const someNames = {
catName: 'purry',
rabbitName: 'floppy',
turtleName: 'shelly'
};
const { catName, dogName, hamsterName, rabbitName } = someNames;
const animalNames = Object.assign({}, {
catName,
dogName,
hamsterName,
rabbitName
});
console.log(animalNames);// {catName: 'purry', rabbitName: 'floppy'}
实际记录的内容是:
{
catName: 'purry',
dogName: undefined,
hamsterName: undefined,
rabbitName: 'floppy'
}
答案 0 :(得分:5)
请勿使用Object.assign
复制所有自己的可枚举属性,无论其值如何,但您自己的自定义函数可以过滤掉undefined
属性:
function assignDefined(target, ...sources) {
for (const source of sources) {
for (const key of Object.keys(source)) {
const val = source[key];
if (val !== undefined) {
target[key] = val;
}
}
}
return target;
}
…
const animalNames = assignDefined({}, {
catName,
dogName,
hamsterName,
rabbitName
});
答案 1 :(得分:2)
这是我之后的目的。它只是@ Bergi代码的重构。我这样做是因为它的循环次数减少了。 @ Bergi的答案允许尽可能多的对象参数。在此解决方案中,如果您在babel(https://babeljs.io/docs/plugins/transform-object-rest-spread/)中启用了对象展开,则可以使用展开来创建第二个对象。
const someNames = {
catName: 'purry',
rabbitName: 'floppy',
turtleName: 'shelly'
};
function assignDefined(target, source) {
Object.keys(source).map((key, index) => {
if(source[key] !== undefined) {
target[key] = source[key];
}
});
return target;
}
const { catName, dogName, hamsterName, rabbitName } = someNames;
const animalNames = assignDefined({}, {
catName,
dogName,
hamsterName,
rabbitName
});
console.log(animalNames);
谢谢@Bergi!
答案 2 :(得分:1)
你可以做这样的事情只是为了清理那些属性
SharedPreferences
答案 3 :(得分:1)
'use strict';
const someNames = {
catName: 'purry',
rabbitName: 'floppy'
};
const expectedProperties = ['catName', 'dogName', 'hamsterName', 'rabbitName'];
const animalNames = Object.assign({}, expectedProperties.reduce((o, prop) => (someNames[prop]) ? (o[prop] = someNames[prop]) && o : o, {}));
console.log(animalNames);
答案 4 :(得分:1)
旧线程,但是对以前的答案不太满意。以为我会选择更干净的解决方案:
const someNames = {
catName: 'purry',
rabbitName: 'floppy',
notAnAnimal: 'car',
};
const allowedKeys = ['catName', 'rabbitName'];
const animalNames = Object.keys(someNames).reduce((animals, key) => {
if (allowedKeys.includes(key)) animals[key] = someNames[key];
return animals;
}, {});