Clone a JS object except of a key value array item.

huangapple go评论63阅读模式
英文:

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: &quot;customer information&quot;,
  inputs: [
    { key: &quot;customerAccount&quot; },
    { key: &quot;customerCity&quot; }
  ]
};
let res = {...inputsCustomer, inputs: 
  inputsCustomer.inputs.filter(x =&gt; x.key !== &#39;customerAccount&#39;)};
console.log(res);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 23:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定