我有一个这样的数组:
const arr = [{name: 'mm', status: 200, response: {size: 1173, code: 0, data: {image: 'aa.png', abs_image: 'fwefwesa.jpg'}}},{name: 'gg', status: 200,response: {size: 1133, code: 0, data: {image: 'bb.png', abs_image: 'fwefwerwea.jpg'}}},{name: 'gg', status: 200, response: {size: 1133, code: 0,data: {image: 'cc.png', abs_image: 'fwefwerwea.jpg'}}}]
我是否有任何方法可以用来从image
销毁arr
属性,我将从中获取['aa.jpg', 'bb.jpg', 'cc.jpg']
数组。我不想循环数组。
答案 0 :(得分:1)
var imageArray = arr.map(elem => elem.response.data.image)
答案 1 :(得分:1)
通过仅使用数组解构来获取值image
的数组是不可能的,您只能从单个元素获取变量。要获得阵列,您必须执行以下操作:
const arr = [{name: 'mm', status: 200, response: {size: 1173, code: 0, data: {image: 'aa.png', abs_image: 'fwefwesa.jpg'}}},{name: 'gg', status: 200,response: {size: 1133, code: 0, data: {image: 'bb.png', abs_image: 'fwefwerwea.jpg'}}},{name: 'gg', status: 200, response: {size: 1133, code: 0,data: {image: 'cc.png', abs_image: 'fwefwerwea.jpg'}}}]
const [ {response: { data: { image } } }, {response: { data: { image: image2 } } }, {response: { data: { image: image3 } } }] = arr;
console.log([image, image2, image3]);
确实让人感觉到了。相反,您可以在该数组上调用map,无论是否有参数析构化:
const arr = [{name: 'mm', status: 200, response: {size: 1173, code: 0, data: {image: 'aa.png', abs_image: 'fwefwesa.jpg'}}},{name: 'gg', status: 200,response: {size: 1133, code: 0, data: {image: 'bb.png', abs_image: 'fwefwerwea.jpg'}}},{name: 'gg', status: 200, response: {size: 1133, code: 0,data: {image: 'cc.png', abs_image: 'fwefwerwea.jpg'}}}]
const imageArr = arr.map(({ response: { data: { image }}}) => image);
const imageArr2 = arr.map((item) => item.response.data.image);
console.log(imageArr);
console.log(imageArr2);