Frank Mochoge
Frank Mochoge

Reputation: 5

Filter json response using values from another array containing keys

I am trying to get the values from a JSON response, using key values contained in a different array. My code is as below but I am getting undefined when I try to log the results.

let fdName =["SerialNo","denDate","denShift","denTime","denWs_1","denWs_2","denVol_1","denVol_2","denPwdrMix"];

let dtValue = [{
id: 1,
SerialNo: 1,
denDate: "2019-09-09",
denShift: "Day",
denTime: "10:32:00",
denWs_1: 10.23,
denWs_2: 11.2,
denVol_1: 12.5,
denVol_2: 10.12,
denPwdrMix: 0.75,
created_at: null,
updated_at: null
}];

var savedData = fdName.map(function(e) {
    var filteredRes = dtValue.find(a => a[key] == e);
return filteredRes ;});

console.log(savedData);

expected results: [1, 2019-09-09, Day, 10:32:00, 10:23, 11.2, 12.5, 10.12, 0.75];

I would like to display the obtained results in a table using v-for as below

<tbody>
 <tr>
  <td
    v-for="(dtValue, sdtValue ) in savedData "
     :key="sdtValue"
      >     
       {{dtValue}}
 </td>
  </tr>
 </tbody>

Upvotes: 0

Views: 69

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

If you want to map based on fdName, you will need 2 loop to render the result.

let fdName =["SerialNo","denDate","denShift","denTime","denWs_1","denWs_2","denVol_1","denVol_2","denPwdrMix"];

let dtValue = [{
  id: 1,
  SerialNo: 1,
  denDate: "2019-09-09",
  denShift: "Day",
  denTime: "10:32:00",
  denWs_1: 10.23,
  denWs_2: 11.2,
  denVol_1: 12.5,
  denVol_2: 10.12,
  denPwdrMix: 0.75,
  created_at: null,
  updated_at: null
}];

var savedData = dtValue.map((e) => fdName.map(key => e[key]));

console.log(savedData);

Then the table will be:

<tbody>
  <tr v-for="data in savedData">
    <td v-for="value in data">     
      {{value}}
    </td>
  </tr>
</tbody>

Of you can render without map then need only one loop but need to list all the field. Example:

<tbody>
  <tr v-for="data in dtValue">
    <td>{{data[key1]}}</td>
    <td>{{data[key2]}}</td>
    <td>{{data[key3]}}</td>
    <td>{{data[key4]}}</td>
    <td>{{data[key5]}}</td>
  </tr>
</tbody>

Upvotes: 1

Related Questions