我有一个如下所示的数组
var someData = [“123”,“456”];
我正在尝试从上面的
创建以下JSON[{
"link_video": "123",
"video_id":456
}, {
"link_video": "456"
"video_id": "123"
}]
我试过以下
var myvideos = [];
var someData = ["123", "456"];
for (var i = 0; i < someData.length; i++) {
myvideos.push({
"link_video": someData[i],
"video_id": someData[i],
});
}
console.log(JSON.stringify(myvideos));
但正在形成的输出是
[{"link_video":"123","video_id":"123"},{"link_video":"456","video_id":"456"}]
http://jsfiddle.net/cod7ceho/465/
你能否告诉我如何正确地形成这个JSON
答案 0 :(得分:3)
好吧,你需要为每次迭代访问数组中的两个元素,所以你应该更新你的循环,然后通过访问索引i
的元素及其在数组中的直接兄弟来追加对象两次: / p>
var myvideos = [];
var someData = ["123", "456"];
for (var i = 0; i < someData.length; i+=2)
{
myvideos.push({
"link_video": someData[i],
"video_id": someData[i+1],
},
{
"link_video": someData[i+1],
"video_id": someData[i],
});
}
console.log(myvideos);
&#13;
答案 1 :(得分:1)
试试他的,这可能就是你要找的东西
还有更多数据,例如@font-face {
font-family: 'SunriseInternational';
src: url('fonts/SunriseInternational.otf') format('otf'),
url('fonts/SunriseInternational.ttf') format('truetype');
unicode-range: U+20-21, U+3F, U+41-5A, U+61-7A;
}
h1,
h2,
.h1,
.h2 {
font-family: 'SunriseInternational', 'Branding-Medium', sans-serif;
font-size: 8vw;
color: #ffffff;
letter-spacing:2px;
}
["123", "456", "789"]
var myvideos = [];
var someData = ["123", "456"];
for (var i = 0; i < someData.length; i++) {
myvideos.push({
"link_video": someData[i],
"video_id": someData[(i == 0 ? (i + 1) : i == (someData.length - 1) ? (0) : (i + 1))],
});
}
console.log(JSON.stringify(myvideos));
答案 2 :(得分:-1)
只需手动喜欢这个lol
var myvideos = [];
var someData = ["123", "456"];
console.log(JSON.stringify([{"link_video": someData[0], "video_id": someData[1]}, {"link_video": someData[1], "video_id": someData[0]}]));
&#13;