将对象数组转换为小写

时间:2018-02-05 10:47:32

标签: javascript arrays node.js

Array看起来像这样:

"myTags":
[{
  "type":"one",
  "value":"Testing",
  "note":"Hey"
},{
  "type":"two",
  "value":"Yg5GE",
  "note":"hey2"
}]

我需要转换类型:'一个'价值'测试'小写,即值=测试需要进行测试'有没有办法保持相同的结构?

注意:"type":"one","value":"Testing",可能并不总是包含在数组中。所以我想在这种情况下我首先需要检查它们是否存在?

我试过.map,但是我无法得到我想要的结果。任何帮助,将不胜感激。

理想结构:

  "myTags":
  [{
    "type":"one",
    "value":"testing",
    "note":"hey"
  },{
    "type":"two",
    "value":"Yg5GE",
    "note":"hey2"
  }]

2 个答案:

答案 0 :(得分:1)

迭代myTags中的元素,检查type是否为"one",然后才将value的内容更改为小写(如果存在)



var data = {
  "myTags": [{
    "type": "one",
    "value": "Testing",
    "note": "Hey"
  }, {
    "type": "one",
    "note": "Hey"
  }, {
    "type": "two",
    "value": "Yg5GE",
    "note": "hey2"
  }]
};

data.myTags.forEach(function(tag) {
  if (tag.type === "one" && typeof tag.value !== "undefined") {
    tag.value = tag.value.toLowerCase();
  }
});

console.log(data.myTags);




您也可以先过滤myTags的内容,以获取"type": "one"的元素,并仅迭代这些元素



var data = {
  "myTags": [{
    "type": "one",
    "value": "Testing",
    "note": "Hey"
  }, {
    "type": "one",
    "note": "Hey"
  }, {
    "type": "two",
    "value": "Yg5GE",
    "note": "hey2"
  }]
};

data.myTags
    .filter(function(tag) {
      return tag.type === "one";
    })
    .forEach(function(tag) {
      if (typeof tag.value !== "undefined") {
        tag.value = tag.value.toLowerCase();
      }
    });

console.log(data.myTags);




答案 1 :(得分:0)

这个完美无缺

 $(document).ready(function(){

 var objects ={"myTags":

 [{"type":"one","value":"Testing", "note":"Hey"}

 ,{ "type":"two", "value":"Yg5GE", "note":"hey2"}]}; 

  var obj = objects.myTags.map(function(a) { 
  a.value = a.value.toLowerCase();
  return a;

 });
 console.log(obj);
 });

输出:

  {type: "one", value: "testing", note: "Hey"}

  {type: "two", value: "yg5ge", note: "hey2"}

谢谢

相关问题