如何解析[object Object]

时间:2017-08-17 12:13:09

标签: javascript parsing

我不知道如何解析响应中的值。我需要根据单个字符串中的键和值获取值,但无法使其正常工作

这里是我的示例代码

[
{"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]]}]

我希望将campNamepage_visitsfilter_typessearchUrlpageNo值存储为javascript中的字符串

2 个答案:

答案 0 :(得分:2)

您可以将这些值存储在对象中:

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

答案 1 :(得分:1)

您可以使用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);