0

I have this code in 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. the data came from json file using ajax call . this is the return of consolg log

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

any help will be appreciated

4
  • 1
    You can't return a value from $.each afaik; it's meant purely for carrying out side effects. Did you mean to use map? Commented Oct 6, 2017 at 16:20
  • 1
    $.each doesn't return anything. Do you really want to convert objects to strings? Or do you simply want to convert an object of objects to an array of objects? Or is objectStory already an array of objects (in which case you don't have to do anything)? Please explain what you are actually trying to achieve here (see How to Ask). Commented Oct 6, 2017 at 16:21
  • 1
    What is the contents of objectStory, and what is the output you're expecting. There would seemingly be several ways to achieve what you need (spread syntax, map(), forEach(), etc) but the most appropriate depends on your goal. Commented Oct 6, 2017 at 16:27
  • use map instead of .each() Commented Oct 6, 2017 at 16:28

1 Answer 1

2

$.each returns object that it was called with (for chaining with other methods), not string as you would wish. When you need result you should use 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:

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

Otherwise you would have nested arrays under your items key.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.