我有一个来自后端的对象列表,如下
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},
];
我想只提取每个对象的id
和value
键的值,并在
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
}, {})
请在这里查看详细说明我也强烈推荐map
和filter
。对于reduce
,它们是数组
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);