簡體   English   中英

如何以首選格式重組包含對象的數組?

[英]How can an array containing objects be restructured in a preferred format?

給出以下示例:

foobar: [
  {
    "foo": {
      "title": "example title foo"
      "desc": "example description foo"
    }
  },
  {
    "bar": {
      "title": "example title bar",
      "unnecessary": "this is not needed"
      "desc": "example description bar",

    }
  }
]

如何格式化這個包含對象的數組,你會得到以下結果:

[
  {"example title foo": "example description foo"}, 
  {"example title bar": "example description bar"}
]

您可以使用Object.valuesmap 使用計算屬性名稱創建所需的對象

 let foobar = [{"foo":{"title":"example title foo","desc":"example description foo"}},{"bar":{"title":"example title bar","unnecessary":"this is not needed","desc":"example description bar"}}] let output = foobar.map(a => { let { title, desc } = Object.values(a)[0]; return { [title] : desc } }) console.log(output)

您可以獲取單個值的對象,對其進行解構並映射所需的樣式。

 var foobar = [{ foo: { title: "example title foo", desc: "example description foo" } }, { bar: { title: "example title bar", unnecessary: "this is not needed", desc: "example description bar" } }], pattern = ({ title, desc }) => ({ [title]: desc }), result = foobar.map(o => pattern(Object.values(o)[0])); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM