繁体   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