简体   繁体   中英

Transform an array of objects to key value pairs with one of the values as key

I have an array of objects like this:

  const arr = [
{
  question_Number: 205,
  question_Text: "Enter Engine Number",
},
{
  question_Number: 497,
  question_Text: "Whether imported?",
},
{
  question_Number: 547,
  question_Text: "Whether goods are new?",
},
{
  question_Number: 206,
  question_Text: "Select Vehicle Condition",
},

];

and I want to transform it into an object of key/value pairs as this:

  const result = {
205: {
  type: "string",
  title: "Enter Engine Number",
},
497: {
  type: "string",
  title: "Whether imported?",
},
547: {
  type: "string",
  title: "Whether imported goods are new?",
},
206: {
  type: "string",
  title: "Select Vehicle Condition",
},

};

How can I achieve this result using plain javascript or even lodash?

Thanks.

You could map entries with new objects.

 const data = [{ question_Number: 205, question_Text: "Enter Engine Number" }, { question_Number: 497, question_Text: "Whether imported?" }, { question_Number: 547, question_Text: "Whether goods are new?" }, { question_Number: 206, question_Text: "Select Vehicle Condition" }], result = Object.fromEntries(data.map(({ question_Number, question_Text: title }) => [question_Number, { type: 'string', title }])); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You can do this with built in things but I think this would be more understandable to see what is going on, something real quick:

 const input = [ { question_Number: 205, question_Text: "Enter Engine Number", }, { question_Number: 497, question_Text: "Whether imported?", }, { question_Number: 547, question_Text: "Whether goods are new?", }, { question_Number: 206, question_Text: "Select Vehicle Condition", } ] const transformArray = (arr) => { let result = {} for (let i = 0; i < arr.length; i++) { result[arr[i].question_Number] = { type: typeof arr[i].question_Text, title: arr[i].question_Text } } return result } console.log(transformArray(input))

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