如何从对象中获取特定值?

时间:2017-12-14 14:02:10

标签: jquery object

我正在创建一个对象,并希望输出id

的值

   var result = {};
  $.each($('.color input').serializeArray(), function() {
      result[this.name] = this.value;
  });  
  
  console.log(result[id]);
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>

我期望的结果是23

3 个答案:

答案 0 :(得分:2)

您必须致电result['id']result.id,因为id未被声明为变量

&#13;
&#13;
   var result = {};
  $.each($('.color input').serializeArray(), function() {
      result[this.name] = this.value;
  });  
  
  console.log(result.id);
  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

首先,您需要从对象获取namevalue属性,该属性可以作为第二个参数。并使用['id'] or .id语法获取属性。

&#13;
&#13;
var result = {};
$.each($('.color input').serializeArray(), function(i, v) {
  result[v.name] = v.value;
});

console.log(result.id);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
  <input type="hidden" name="name" value="fred">
  <input type="hidden" name="id" value="23">
</div>
&#13;
&#13;
&#13;

或者通过在jQuery输入元素集合上简单地使用each()方法迭代来生成对象。

&#13;
&#13;
var result = {};
$('.color input').each(function() {
  result[this.name] = this.value;
});

console.log(result.id);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
  <input type="hidden" name="name" value="fred">
  <input type="hidden" name="id" value="23">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您收到的错误是因为浏览器认为id是变量。您需要通过result['id']result.id访问它才能从对象获取属性的值:

示例1: 使用括号表示法访问属性值

&#13;
&#13;
   var result = {};
  $.each($('.color input').serializeArray(), function() {
      result[this.name] = this.value;
  });  
  
  console.log(result['id']);
  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
&#13;
&#13;
&#13;

示例2: 使用对象表示法访问属性值

&#13;
&#13;
   var result = {};
  $.each($('.color input').serializeArray(), function() {
      result[this.name] = this.value;
  });  
  
  console.log(result.id);
  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
&#13;
&#13;
&#13;