简体   繁体   English

从JavaScript中的JQuery.each()返回对象

[英]Returning an object from JQuery.each() in JavaScript

I have this code in JavaScript 我在JavaScript中有这段代码

lastUpdated: 1492665454,
  items:

  [
    $.each(objectStory, function(key, value) {
      //key + ": " + value ;
      //console.log(value)
      console.log(JSON.stringify(value));
      //document.write(sitem);

      return JSON.stringify(value);
    }),
  ]

}]

the console.log is print the object as I wanted but the return function doesn't work. console.log根据需要打印对象,但是返回功能不起作用。 the data came from json file using ajax call . 数据来自使用ajax调用的json文件。 this is the return of consolg log 这是consolg日志的返回

{"id":"87","type":"image","src":"url/IMG_2363.MOV"}

any help will be appreciated 任何帮助将不胜感激

$.each returns object that it was called with (for chaining with other methods), not string as you would wish. $.each返回调用对象(用于与其他方法链接),而不是您希望的字符串。 When you need result you should use map `. 当你需要得到你应该使用map `。 Please take a look at the snippet showing the difference: 请查看显示差异的代码段:

 var objectStory = { k1: 1, k2: 2, k3: 3 } var eachResult = $.each(objectStory, function(key, value) { return JSON.stringify(value); }); var mapResult = $.map(objectStory, function(value) { return JSON.stringify(value); }); console.log(eachResult); console.log(mapResult); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

In your code you should assign value to key items this way: 在代码中,您应该通过以下方式为关键items分配值:

var obj = {
    // other fields
    items: $.map(objectStory, function(value) {
       return JSON.stringify(value);
    })
};

Otherwise you would have nested arrays under your items key. 否则,您将在items键下嵌套数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM