找到特定属性然后推送到数组

时间:2016-03-26 04:35:47

标签: javascript

我必须使用以下json文件。我的目标是正确地找到所有name并将其值添加到name数组。

var data = {
  "Fruits": [{
    "name": "apple",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "orange",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "strawberry",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "banana",
    "added_date": "",
    "expired_date": ""
  }],
  "Meat": [{
    "name": "beef",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "chicken",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "fish",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "pork",
    "added_date": "",
    "expired_date": ""
  }],
  "Vegetable": [{
    "name": "cucumber",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "kale",
    "added_date": "",
    "expired_date": ""
  }],
  "Spice": [{
    "name": "cajun",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "garlic",
    "added_date": "",
    "expired_date": ""
  }]
};

我想出了类似的东西,但在push函数上给我错误。有没有更好的方法来解决这个问题?

var name = [];
for (var key in data) {
  for (var i = 0; i < data[key].length; i++) {
    console.log(data[key][i].name);
    name.push(data[key][i].name);
  }
}
console.log(name);

1 个答案:

答案 0 :(得分:5)

问题是变量名name,因为它在全局范围内,您试图覆盖只接受字符串值的window.name属性

&#13;
&#13;
var data = {
  "Fruits": [{
    "name": "apple",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "orange",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "strawberry",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "banana",
    "added_date": "",
    "expired_date": ""
  }],
  "Meat": [{
    "name": "beef",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "chicken",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "fish",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "pork",
    "added_date": "",
    "expired_date": ""
  }],
  "Vegetable": [{
    "name": "cucumber",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "kale",
    "added_date": "",
    "expired_date": ""
  }],
  "Spice": [{
    "name": "cajun",
    "added_date": "",
    "expired_date": ""
  }, {
    "name": "garlic",
    "added_date": "",
    "expired_date": ""
  }]
};

var name = [];
snippet.log('name value:' + name + ':' + typeof name + ':')

var names = [];
for (var key in data) {
  for (var i = 0; i < data[key].length; i++) {
    names.push(data[key][i].name);
  }
}
snippet.log(names);
&#13;
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;