如何从对象数组创建一个键值对对象的字符串?



我有一个来自后端的对象列表,如下

const paramData = [
{id: "search_type", value: "All items", required: true},
{id: "time_period", value: "Week", required: false},
{id: "user_type", value: "All Users", required: false},
{id: "question_type", value: "Multiple questions", required: true},
];

我想只提取每个对象的idvalue键的值,并在

下面创建类似的内容
const extractedData = "{"search_type": "All items", "time_period": "Week", "user_type": "All Users", "question_type": "Multiple questions"}";

实现这一目标的最佳方式是什么?

您可以使用reduce;

const extractedData = paramData.reduce((obj, item) => {
obj[item.id] = item.value
return obj
}, {})

请在这里查看详细说明我也强烈推荐mapfilter。对于reduce,它们是数组

的3颗星

ilkerkaran的另一个解决方案是:

const paramData = [{
id: "search_type",
value: "All items",
required: true
}, {
id: "time_period",
value: "Week",
required: false
}, {
id: "user_type",
value: "All Users",
required: false
}, {
id: "question_type",
value: "Multiple questions",
required: true
},];
var extractedData = "";
for (var i in paramData) {
extractedData += `"${paramData[i].id}": "${paramData[i].value}", `;
}
extractedData = `{${extractedData.slice(0, -2)}}`;
console.log(extractedData);

相关内容

  • 没有找到相关文章

最新更新