Danish
Danish

Reputation: 704

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.

Upvotes: 2

Views: 60

Answers (2)

Brixi
Brixi

Reputation: 61

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386858

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

Upvotes: 4

Related Questions