Home > Back-end >  Transform an array of objects to key value pairs with one of the values as key
Transform an array of objects to key value pairs with one of the values as key

Time:01-25

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.

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related