我有一个对象“ myData”的数组。我需要创建一个对象“ newMyData”的新数组
以下是“ myData”
myData = [
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
},
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
}, .........
]
我需要动态创建新的对象数组,如下所示:“ myData”
newMyData = [
{
"mainImage": "~/images/test.png",
"ThumbImage": "~/thumbnail/test.png"
},
{
"mainImage": "~/images/test.png",
"ThumbImage": "~/thumbnail/test.png"
}, .........
]
我需要编写什么javascript函数?如何遍历所有节点。
答案 0 :(得分:2)
myNewData = myData.map(data => ({
mainImage: data.PictureUrl,
thumbImage: data.ThumbnaiUrl // please, use lowerCase for properties.
}));
答案 1 :(得分:2)
使用数组映射:
myData = [
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
},
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
},
];
var newMyData = myData.map(current=>{
var obj = {};
obj.mainImage = current.PictureUrl;
obj.ThumbImage = current.ThumbnailUrl;
return obj;
});
console.log(newMyData);
答案 2 :(得分:0)
Use可以简单地使用Arrays.forEach()
遍历您的数组,并在map中获取所需的值,然后像下面这样最终将该map推入您的新数组中:
var newMyData = [];
var myData = [
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
},
{
"PictureUrl": "~/images/test.png",
"ThumbnailUrl": "~/thumbnail/test.png",
"Date": "02/08/2018",
"Time": "09.00.00AM",
"ImageName": "NewImage"
}
];
myData.forEach(function(data) {
var newMap = {};
newMap.mainImage = data.PictureUrl;
newMap.ThumbImage = data.ThumbnailUrl;
newMyData.push(newMap);
});
console.log(newMyData);