Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-

I am receiving a json response from an API call. I need to store its keys, and create an array of an object. I am intending to this array of an object is created dynamically no matter the keys of the response.

I've already got the keys like this:

  const json_getAllKeys = data => {
   const keys = data.reduce((keys, obj) => (
      keys.concat(Object.keys(obj).filter(key => (
        keys.indexOf(key) === -1))
      )
    ), [])
    return keys 
}

That returned an array (using a sample json):

['name','username', 'email']

But I am trying to use that array to create an array of object that looks like this one

[
    {
      name: "name",
      username: "username",
      email: "Email",
    }
];

I've been trying mapping the array, but got multiple objects because of the loop, and I need a single one to make it work.

keys.map(i=>({i:i}))

[
  { i: 'id' },
  { i: 'name' },
  { i: 'username' },
  { i: 'email' }
]

Any hint would be useful!

Thanks in advance :D

question from:https://stackoverflow.com/questions/65894876/from-single-array-convert-to-an-array-of-object-with-keys-coming-from-a-json-res

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you're looking for is Object.fromEntries, which is ECMA2019, I believe, so available in Node >=14 and will be provided as a polyfill if you employ babel.

I can't quite discern what your reduce should produce, but given the sample input, I would write

const input = ['name','username', 'email'];

const result = Object.fromEntries(input.map(name => ([name, name])));
// result == { name: 'name', username: 'username', email: 'email' }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...