我有一个类似这样的对象:
{
"sample.JPG": {
"id": "c9a29270",
"filename": "sample.JPG"
},
"test.JPG": {
"id": "c6a270",
"filename": "test.JPG"
},
"sample1.JPG": {
"id": "c70",
"filename": "sample1.JPG"
},
"test2.JPG": {
"id": "c6a",
"filename": "test2.JPG"
}
}并希望它是这样的:
[["fakepath/sample.JPG", "c9a29270"], ["fakepath/test.JPG", "c6a270"]]在这里,伪路径只表示静态/硬编码路径
我尝试的是
Object.keys(myobj).map((key)=> {
return myoby[key];
});但是结果符合我的需要,有什么建议吗?
我做了这样的事情:
for(var i in obj){
this.arr.push(['fakepath/' + i,obj[i].id])
}可以吗?
发布于 2019-05-07 14:57:04
你可以在Object.values上使用map(),它非常简洁,而且比循环更容易阅读:
let o = {"sample.JPG": {"id": "c9a29270","filename": "sample.JPG"},"test.JPG": {"id": "c6a270","filename": "test.JPG"},"sample1.JPG": {"id": "c70","filename": "sample1.JPG"},"test2.JPG": {"id": "c6a","filename": "test2.JPG"}}
let arr = Object.values(o).map(({id, filename}) => ['fakepath/' + filename, id])
console.log(arr)
发布于 2019-05-07 14:56:22
您可以使用Object.keys和map。
let obj = { "sample.JPG": { "id": "c9a29270", "filename": "sample.JPG" }, "test.JPG": { "id": "c6a270", "filename": "test.JPG" }, "sample1.JPG": { "id": "c70", "filename": "sample1.JPG" }, "test2.JPG": { "id": "c6a", "filename": "test2.JPG" } }
console.log(Object.keys(obj).map(key=> [`fakepath/${key}`, obj[key].id]));
发布于 2019-05-07 14:56:41
映射对象的Object.entries:
const input = {
"sample.JPG": {
"id": "c9a29270",
"filename": "sample.JPG"
},
"test.JPG": {
"id": "c6a270",
"filename": "test.JPG"
},
"sample1.JPG": {
"id": "c70",
"filename": "sample1.JPG"
},
"test2.JPG": {
"id": "c6a",
"filename": "test2.JPG"
}
};
const output = Object.entries(input)
.map(([key, { id, filename }]) => ([`fakepath/${filename}`, id]))
console.log(output);
https://stackoverflow.com/questions/56017078
复制相似问题