如何从对象数组创建一串键值对对象?

时间:2021-02-25 14:15:58

标签: javascript

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

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

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

2 个答案:

答案 0 :(得分:2)

你可以使用reduce;

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

请看详细说明here 我也强烈推荐 mapfilter。使用 reduce,它们是阵列的 3 颗星

答案 1 :(得分:0)

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