如何从JSON对象获取价值

时间:2019-10-21 10:43:03

标签: javascript arrays json regex replace

在我的Web应用程序中,Web API返回以下JOSN对象。

[ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

我需要通过传递Body从每个JSON节点获取templateID值。问题是您可以在某些地方看到此JSON具有\r\n。但是我需要获取每个节点的Body值。例如,如果我通过1,我需要得到sample date hete hee. Name,如果我通过2,我需要you soon.我该怎么做?

我尝试过了。但不起作用

var data2 = [ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

function usersBasedOnIDs(isShow,field){

    var filtered=data2.filter(function(item){
        return item[field] == isShow;         
    });
    console.log(filtered);
}

usersBasedOnIDs(1,'templateID');

3 个答案:

答案 0 :(得分:3)

item[field] == isShow;  

您没有任何对象可以满足此条件,我想您想根据ID过滤元素,然后查看其主体值

var data2 = [{
    "templateID": 1,
    "template": "{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
  },
  {
    "templateID": 2,
    "template": "{ \"Body\": \"you soon.\" }"
  }
]

function usersBasedOnIDs(isShow, field) {

  var filtered = data2.filter(function(item) {
    return item[field] == isShow;
  });
  console.log(filtered && JSON.parse(filtered[0].template).Body);
}

usersBasedOnIDs(1, 'templateID');

答案 1 :(得分:1)

只需尝试

var x = [ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]
for(let i=0;i<x.length;i++){
  let y = x[i].template;
  console.log(JSON.parse(y).Body);
}

答案 2 :(得分:1)

function usersBasedOnIDs(templateId) {
    let result = data2.find(function(item) {
        return item.templateId === templateId;
    });
    if(result === undefined) {
        return;
    } else {
        return JSON.parse(result.template).Body;
    }
}

console.log(usersBasedOnIDs(1));