2

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.

2
  • the value of type property is always "string"? Commented Jan 24, 2022 at 19:06
  • @SaeedShamloo this is a subset of the data I had, It can also be number or datetime Commented Jan 24, 2022 at 20:26

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.