![](/img/trans.png)
[英]Convert string array of key-value pair to array of objects javascript
[英]How to create a string of key-value pair object from an array of objects?
我有一個來自后端的對象列表,如下所示
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},
];
我想只提取每個 object 的id
和value
鍵的值,並制作如下所示的內容
const extractedData = "{\"search_type\": \"All items\", \"time_period\": \"Week\", \"user_type\": \"All Users\", \"question_type\": \"Multiple questions\"}";
實現這一目標的最佳方法是什么?
你可以使用減少;
const extractedData = paramData.reduce((obj, item) => {
obj[item.id] = item.value
return obj
}, {})
請在此處查看詳細說明我也強烈推薦map
和filter
。 使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.