英文:
Clone a JS object except of a key value array item
问题
我想要复制这个对象,但不包括 { key: "customerAccount" }。
期望的克隆对象:
const newInputsCustomer = {
title: "customer information",
inputs: [
{ key: "customerCity" }
]
};
我尝试过使用解构,但没有成功解决它。
英文:
I have an object:
const inputsCustomer = {
title: "customer information",
inputs: [
{ key: "customerAccount" },
{ key: "customerCity" }
]
};
I want to duplicate this object with out { key: "customerAccount" }.
Expected cloned object:
const newInputsCustomer = {
title: "customer information",
inputs: [
{ key: "customerCity" }
]
};
I've been trying with destructuring but haven't manage to solve it.
答案1
得分: 1
您可以使用扩展语法复制对象,然后使用 Array#filter
保留不带指定键的元素。
const inputsCustomer = {
title: "customer information",
inputs: [
{ key: "customerAccount" },
{ key: "customerCity" }
]
};
let res = {...inputsCustomer, inputs: inputsCustomer.inputs.filter(x => x.key !== 'customerAccount')};
console.log(res);
英文:
You can use spread syntax to copy over the object, then use Array#filter
to keep only the elements without the specified key.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const inputsCustomer = {
title: "customer information",
inputs: [
{ key: "customerAccount" },
{ key: "customerCity" }
]
};
let res = {...inputsCustomer, inputs:
inputsCustomer.inputs.filter(x => x.key !== 'customerAccount')};
console.log(res);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论