[英]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",
},
];
我想將其轉換為鍵/值對的 object,如下所示:
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 來實現這個結果?
謝謝。
您可以使用新對象進行 map 條目。
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.