给出的是一个json对象,如下所示:
var items = [{
title: 'sample 1',
image: 'http://www.lorempixel.com/700/600/'
}, {
title: 'sample 2',
image: 'http://www.lorempixel.com/900/1200/'
}, {
title: 'sample 3',
image: 'http://www.lorempixel.com/400/300/'
}, {
title: 'sample 4',
image: 'http://www.lorempixel.com/600/600/'
}, {
title: 'sample 5',
image: 'http://www.lorempixel.com/400/310/'
}, {
title: 'sample 6',
image: 'http://www.lorempixel.com/410/300/'
}, {
title: 'sample 7',
image: 'http://www.lorempixel.com/500/300/'
}, {
title: 'sample 8',
image: 'http://www.lorempixel.com/300/300/'
}, {
title: 'sample 9',
image: 'http://www.lorempixel.com/450/320/'
}, {
title: 'sample 10',
image: 'http://www.lorempixel.com/500/400/'
}];
我想要一个像这样的数组。
[['sample 1', 'http://www.lorempixel.com/700/600/'], ['sample 2', 'http://www.lorempixel.com/900/1200/'], ....]
我尝试过这样的事情:
const rows = [];
for (let i = 0; i < items.length; i++) {
const element = items[i];
rows[i] = element.title;
for (let j = i; j < items.image; j++) {
const el = response[j];
rows[j] = el.image;
}
}
我想得到一个仅包含所有图像的数组,我想是因为我在第二个循环中覆盖了其他值。什么是正确的方式来获得两个所述的值?
答案 0 :(得分:2)
只需将Object.values()
作为回调传递给.map()
:
let data = [
{title: 'sample 1', image: 'http://www.lorempixel.com/700/600/'},
{title: 'sample 2', image: 'http://www.lorempixel.com/900/1200/'},
{title: 'sample 3', image: 'http://www.lorempixel.com/400/300/'},
{title: 'sample 4', image: 'http://www.lorempixel.com/600/600/'},
{title: 'sample 5', image: 'http://www.lorempixel.com/400/310/'}
];
let result = data.map(Object.values);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您只需要一个简单的.map
-从对象中提取适当的属性值,然后返回包含这两个值的数组:
var items=[{title:'sample 1',image:'http://www.lorempixel.com/700/600/'},{title:'sample 2',image:'http://www.lorempixel.com/900/1200/'},{title:'sample 3',image:'http://www.lorempixel.com/400/300/'},{title:'sample 4',image:'http://www.lorempixel.com/600/600/'},{title:'sample 5',image:'http://www.lorempixel.com/400/310/'},{title:'sample 6',image:'http://www.lorempixel.com/410/300/'},{title:'sample 7',image:'http://www.lorempixel.com/500/300/'},{title:'sample 8',image:'http://www.lorempixel.com/300/300/'},{title:'sample 9',image:'http://www.lorempixel.com/450/320/'},{title:'sample 10',image:'http://www.lorempixel.com/500/400/'}];
console.log(
items.map(({ title, image }) => [title, image])
);