将对象数组转换为以其中一个值作为键的键值对

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

我有一个这样的对象数组:

  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",
},

];

我想将它转换为一个 key/value 对的对象,如下所示:

  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",
},

};

如何使用纯 javascript 甚至 lodash 实现此结果?

谢谢。

您可以将条目映射到新对象。

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

你可以用内置的东西来做到这一点,但我认为这会更容易理解,看看发生了什么,真正快速的事情:

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