0

I have a list of objects coming from the backend like below

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

I would like to extract the values of only the id and the value key of each object and make something like below

  const extractedData = "{\"search_type\": \"All items\", \"time_period\": \"Week\", \"user_type\": \"All Users\", \"question_type\": \"Multiple questions\"}";

What would be the optimum way to achieve this?

2 Answers 2

2

You can use reduce;

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

Please see detailed description here I also strongly recommend map and filter. With reduce, they are 3 stars of array

Sign up to request clarification or add additional context in comments.

Comments

0

An alternative solution to ilkerkaran's one could be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.