I have an object like:
{
"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"
}
}
and want it to be like:
[["fakepath/sample.JPG", "c9a29270"], ["fakepath/test.JPG", "c6a270"]]
here fake path means nothing but a static/hardcoded path
what I tried was
Object.keys(myobj).map((key)=> {
return myoby[key];
});
but the result was fit to my need any suggestions?
I did something like this:
for(var i in obj){
this.arr.push(['fakepath/' + i,obj[i].id])
}
is it OK?
You can map()
over Object.values
which is pretty concise and easier to read than a loop:
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)
You could use Object.keys
and 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]));
Map the Object.entries
of the object:
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);
Try this
const src = {
"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"
}
};
function objToAr(obj){
let result = [];
for(key in obj){
let innerObj = obj[key];
result.push([`fakepath/${innerObj.filename}`, innerObj.id]);
}
return result;
}
console.log(objToAr(src))
You could use Array.from
with Object.values
by using the mapping function to map each object to an array with the path and the id:
const 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"}} const res = Array.from(Object.values(obj), ({id, filename}) => [`fakepath/${filename}`, id]); console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.