多数组JavaScript [关闭]

Hello who can help me with this? I have a json and I parse it, after that for each item i need to create an array

This is my json:

  0: Object
    title: "title0"
    content: "content0"
    comment: "comment0"
  1: Object
    title: "title1"
    content: "content1"
    comment: "comment1"

I have a function

var mystockinfo = [];

function uploadSomething(data){
  var myjsonparse = JSON.parse(data.div);
  for (var i = 0; i < myjsonparse.length;){
        mystockinfo[i][0] = myjsonparse[i].title;
        mystockinfo[i][1] = myjsonparse[i].content;
        mystockinfo[i][2] = myjsonparse[i].comment;
    i++;
  }
}

console.log(mystockinfo);

I need to have

[ 0 => [title0, content0, comment0], 1 => [title1, content1, comment1]]

Can you please help me with this???

Using .map() is an easy way to loop through the array and transforming it into the nested arrays you need.

var obj = [{
  title: "title0",
  content: "content0",
  comment: "comment0"
}, {
  title: "title1",
  content: "content1",
  comment: "comment1"
}];

var updated = obj.map(function(ind) {
  return [ind.title, ind.content, ind.comment];
});

console.log(updated);

</div>

The JSON you have provided is invalid. I am assuming that you cannot use an array but you could borrow methods from Array.prototype to help format the data.

I have set the length automatically in the reduceToValues function if it is not already set.

The one issue with it is that it will return an actual array not an array like object. if you need an array like object out the other end you could reduce the array to an object.

See inline comments for more.

var data = {
  0: {
    title: "title0",
    content: "content0",
    comment: "comment0"
  },
  1: {
    title: "title1",
    content: "content1",
    comment: "comment1"
  }
}

function reduceToValues( data ){
  // if you add a length property to the object it will be array like
  // then you can use the native array methods with it.
  data.length = data.length || Object.keys(data).length;
  // map the array like object to a single array
  return Array.prototype.map.call( data, function( item ){
    var values = [];
    // loop through the object and save the values
    for( var key in item ){
      values.push( item[key] );
    }
    // return the values
    return values;
  }, []);
}

function arrayToArrayLikeObject( arr ){
  return arr.reduce(function( ret, item, ii ){
    ret[ ii ] = item;
    return ret;
  }, {});
}

console.log( reduceToValues( data ) );
// if you need an array like object out the other end
console.log( arrayToArrayLikeObject( reduceToValues( data ) ) );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

</div>