简体   繁体   中英

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

Given the following example:

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

    }
  }
]

How to format this array containing objects that you get the following result:

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

You could use Object.values and map . Use Computed property names to create the desired object

 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)

You could get a single value's object, destructure it and map the wanted style.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM