我有这个对象数组对象
[
{
"id": "1",
"images": [
{
"filename": "some image name",
"type": "gallery"
},
{
"filename": "some image name",
"type": "main"
},
{
"filename": "some image name",
"type": "gallery"
}
]
},
{
"id": "2",
"images": [
{
"filename": "some image name",
"type": "gallery"
},
{
"filename": "some image name",
"type": "main"
},
{
"filename": "some image name",
"type": "gallery"
}
]
}
]
我想更改为“type”:“main”首先为数组中的每个对象。
我想达成这个目标:
[
{
"id": "1",
"images": [
{
"filename": "some image name",
"type": "main"
},
{
"filename": "some image name",
"type": "gallery"
},
{
"filename": "some image name",
"type": "gallery"
}
]
},
{
"id": "2",
"images": [
{
"filename": "some image name",
"type": "main"
},
{
"filename": "some image name",
"type": "gallery"
},
{
"filename": "some image name",
"type": "gallery"
}
]
}
]
对于每个对象,只有一个图像可以是主图像,其余图像可以是图库。
我试图用lodash完成我的目标:
vm.products.forEach(function(item) {
_.map(_.sortBy(item.images, 'type'), 'main');
});
但它不起作用。
我也试过用这个:
var data = _.sortBy(vm.products[0].images, ['type', 'desc']).reverse();
但它只采用了第一个对象。
vm.products
是主数组对象容器
答案 0 :(得分:0)
以下是您想要的。最重要的是嵌套的map语句。您可以提取这些功能并为其指定适合您所在域名的名称,例如' sanitizeImages'什么的。
const data = getData(),
expectedResult = getExpectedResult();
const result = _.map(data, obj => {
obj.images = _.map(obj.images, (imageObj, idx) => {
imageObj.type = (idx === 0)
? 'main'
: 'gallery';
return imageObj;
});
return obj;
});
document.getElementById('result').textContent = _.isEqual(result, expectedResult)
? 'passed'
: 'failed'
// helper functions
function getData() {
return [
{
id: "1",
images: [
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (2).png",
type: "gallery",
$$hashKey: "object:31"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM.png",
type: "main",
$$hashKey: "object:32"
}
]
},
{
id: "2",
images: [
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (2).png",
type: "gallery",
$$hashKey: "object:31"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM.png",
type: "main",
$$hashKey: "object:32"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (3).png",
type: "gallery",
$$hashKey: "object:33"
}
]
}
];
}
function getExpectedResult() {
return [
{
id: "1",
images: [
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (2).png",
type: "main",
$$hashKey: "object:31"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM.png",
type: "gallery",
$$hashKey: "object:32"
}
]
},
{
id: "2",
images: [
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (2).png",
type: "main",
$$hashKey: "object:31"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM.png",
type: "gallery",
$$hashKey: "object:32"
},
{
filename: "Screen Shot 2018-01-25 at 10.14.48 AM (3).png",
type: "gallery",
$$hashKey: "object:33"
}
]
}
];
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<h3 id="result"></h3>
&#13;