multi array JavaScript
multi array JavaScript
你好,谁能帮我?我有一个json并解析它,之后我需要为每个项目创建一个数组
这是我的json:
0: Object
title: "title0"
content: "content0"
comment: "comment0"
1: Object
title: "title1"
content: "content1"
comment: "comment1"
我有一个功能
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);
我需要
[ 0 => [title0, content0, comment0], 1 => [title1, content1, comment1]]
你能帮我做这个吗???
您提供的JSON无效。我假设您不能使用数组,但可以借用array.prototype中的方法来帮助格式化数据。
如果尚未设置,我已在reduceToValues
函数中自动设置长度。
它的一个问题是,它将返回一个实际的数组,而不是类似数组的对象。如果在另一端需要一个类似数组的对象,可以将数组简化为一个对象。
有关详细信息,请参阅内联注释。
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>
使用.map()
是一种简单的方法,可以循环遍历数组并将其转换为所需的嵌套数组。
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);
相关文章:
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- JavaScript Array unshift() 以一种不可变的方式
- AJAX - Javascript array to php
- unset javascript array for
- 构造 JavaScript Array 原型方法
- 将 JavaScript Array.slice + 隐式扩展转换为 C++ vector
- JavaScript Array
- Javascript Array 的求和函数问题
- Javascript Array 的可读性
- 循环遍历 Javascript Array
- 带有多个布尔键的JavaScript Array.sort()
- JavaScript array[“index”].push() 不起作用
- Javascript array alllocation
- 在我执行alert()之前,Javascript array.length为0
- JavaScript array.push (object) with Angular ng-repeat 无法按预期运
- PHP to Javascript Array
- the meaning of jQuery javascript: Array.prototype.slice.call
- Javascript array to NSArray in Xcode
- Javascript Array 作为 BLOB(MIME TEXT 而不是 IMAGE)保存到 mySQL 数据库中
- Javascript array.length 为 0,但数组填充了 40 个项目