Saya tidak tahu cara mengurai nilai dari respons. Saya perlu mendapatkan nilai sesuai dengan kunci dan nilai dalam string individual tetapi tidak dapat membuatnya berfungsi

ini contoh kode saya

[
{"columns":
["campName","page_visits","filter_types","searchUrl","pageNo"],
"values":[["kk","2","All","https://www.google.com/search/results/people/?keywords=kk&origin=SWITCH_SEARCH_VERTICAL",1]]}]

Saya ingin nilai campName,page_visits,filter_types,searchUrl,pageNo disimpan sebagai string dalam javascript

0
batMan007 17 Agustus 2017, 15:13

2 jawaban

Jawaban Terbaik

Anda dapat menyimpan nilai-nilai ini dalam sebuah objek:

const data = [{
  "columns": ["campName", "page_visits", "filter_types", "searchUrl", "pageNo"],
  "values": [
    ["kk", "2", "All", "https://www.google.com/search/results/people/?keywords=kk&origin=SWITCH_SEARCH_VERTICAL", 1]
  ]
}]

const result = data[0].columns.reduce((acc, curr, index) => {
  acc[curr] = data[0].values[0][index];
  
  return acc;
}, {});

console.log(result);
2
Erazihel 17 Agustus 2017, 12:19

Anda dapat membuat objek menggunakan array#reduce

var arr = [{"columns":["campName","page_visits","filter_types","searchUrl","pageNo"],"values":[["kk","2","All","https://www.google.com/search/results/people/?keywords=kk&origin=SWITCH_SEARCH_VERTICAL",1]]}];

var result = arr[0].columns.reduce((o, a, i) => {
  o[a] = arr[0].values[0][i];
  return o;
}, Object.create(null));

console.log(result);
1
Hassan Imam 17 Agustus 2017, 12:22