0

I want to generate this kind of structure based on the data which I am getting from server. The array looks like this

this.topics = [{
  "name": "beauty",
  "selected": false
}, {
  "name": "career",
  "selected": false
}, {
  "name": "childcare",
  "selected": false
}, {
  "name": "crafts",
  "selected": false
}, {
  "name": "culture",
  "selected": false
}, {
  "name": "fashion",
  "selected": true
}, {
  "name": "finances",
  "selected": true
}, {
  "name": "fitness",
  "selected": false
}, {
  "name": "food",
  "selected": false
}, {
  "name": "health",
  "selected": false
}, {
  "name": "home",
  "selected": true
}, {
  "name": "personal",
  "selected": false
}, {
  "name": "relationships",
  "selected": false
}, {
  "name": "religion",
  "selected": false
}]

So I want to send request with those topics which are selected in this format.

{{ base_url  }}/listings?num_items=1&start=3&topics[]=food&topics[]=home

This is what i want to add &topics[]=food&topics[]=home, so from this.topics I need to take selected: true and take name and add in that topics[]

Krešimir Galić
  • 311
  • 2
  • 14

2 Answers2

2

You may filter the topics based on the selected key first using Array#filter and then apply Array#reduce on the filtered array to generate the URL string:

let topics = [{"name":"beauty","selected":false},{"name":"career","selected":false},{"name":"childcare","selected":false},{"name":"crafts","selected":false},{"name":"culture","selected":false},{"name":"fashion","selected":true},{"name":"finances","selected":true},{"name":"fitness","selected":false},{"name":"food","selected":false},{"name":"health","selected":false},{"name":"home","selected":true},{"name":"personal","selected":false},{"name":"relationships","selected":false},{"name":"religion","selected":false}];

let result = '{{ base_url  }}/listings?num_items=1&start=3';
result = topics.filter(item => item.selected)
  .reduce((string, { name }) => `${string}&topics[]=${name}`, result);

console.log(result);
31piy
  • 23,323
  • 6
  • 47
  • 67
2

You could map the topics to their name and add the topics[]= in front and join them by & and add that to the url:

   const topics = this.topics
      .filter(topic => topic.selected)
      .map(topic => "topics[]=" + topic.name)
      .join("&");
   const url = "/listings?num_items=1&start=3&" + topics;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151