gpt4 book ai didi

javascript - 将对象数组转换为键值对,其中一个值作为键

转载 作者:行者123 更新时间:2023-12-02 18:21:24 25 4
gpt4 key购买 nike

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

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

];

我想将其转换为键/值对的对象,如下所示:

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

关于javascript - 将对象数组转换为键值对,其中一个值作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70839139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com