Javascript 操纵和更改原始数组的关键点
我目前正在处理数组/对象中的项目。我以前没有使用过,但在阅读了这个实用工具提供的许多功能后,我决定试一试。我想修改的数组包括添加一个附加对象Javascript 操纵和更改原始数组的关键点,javascript,lodash,Javascript,Lodash,我目前正在处理数组/对象中的项目。我以前没有使用过,但在阅读了这个实用工具提供的许多功能后,我决定试一试。我想修改的数组包括添加一个附加对象sources和更改键。如何使用lodash实现以下目标 电流阵列 var myArr = [{ "flv": "myFile.flvs", "mp4": "myFile.mp4", "webm": "myFile.webm", "thumbnail": "poster.png", "title": "Test",
sources
和更改键。如何使用lodash实现以下目标
电流阵列
var myArr =
[{
"flv": "myFile.flvs",
"mp4": "myFile.mp4",
"webm": "myFile.webm",
"thumbnail": "poster.png",
"title": "Test",
"id": 123456
}];
期望结果
{
data: [
{
sources: [{
file: "myFile.flv"
},{
file: "myFile.mp4"
},{
file: "myFile.webm"
}],
image: 'poster.png',
title: 'Test',
id: '123456'
},
....
]
}
这个怎么样:
var myArr = {
"data": [{
"test1": "myFile.flv",
"test2": "myFile.mp4",
"test3": "myFile.webm",
"thumbnail": "poster.png",
"title": "Test",
"id": 123456
}]
};
var result = _.map(myArr.data, function(el) {
var sources = []
_.each(el, function(v, k) {
if (k.match(/test\d*/) !== null) {
sources.push({
file: v
});
}
});
return {
sources: sources,
image: el.thumbnail,
title: el.title,
id: el.id
};
});
console.log(result);
结果:
按OP请求更新:
var EXTENSIONS = ['flv', 'mp4', 'webm'];
var myArr = [{
"flv": "myFile.flv",
"mp4": "myFile.mp4",
"webm": "myFile.webm",
"thumbnail": "poster.png",
"title": "Test",
"id": 123456
}];
var result = _.map(myArr, function(el) {
var sources = [];
_.each(el, function(v, k) {
if (_.contains(EXTENSIONS, k)) {
sources.push({
file: v
});
}
});
return {
sources: sources,
image: el.thumbnail,
title: el.title,
id: el.id
};
});
console.log(result);
注意:这里我们可以使用u.contains(它是lodash)或EXTENSIONS.indexOf(它是Javascript本机的)。既然您想学习lodash,我想我们应该使用u.contains
更新:刚刚删除。映射函数中的数据,因为OP从源数据中删除了数据属性。是正好有三个
testn
属性,还是任意数字?无论如何,您只需要编写一个transform
函数,然后执行myArr.data=\uu.map(myArr.data,transform)
,对于transform
,我建议用英文或伪代码写下您想要执行的转换,然后将其转换为代码应该很简单。@torazaburo这是一个任意的数字我做了一次修改,而不是数组中的键有testn
,键是flv
,mp4
和webm
@code\Ed\u Student-我看到了更新,你有答案还是还需要帮助?是的,你能告诉我如何使用不同的键吗?再帮我一把,我不得不修改原始数组并取出键数据请参见上面的更新,但是现在我什么都没有得到returned@Code_Ed_Student-只需从map函数中删除.data,所有操作都将重新运行。我更新了答案中的代码。