如何使用JavaScript将对象转换为二维数组

时间:2019-05-07 06:53:34

标签: javascript angular typescript ecmascript-6

我有一个像这样的对象

{
    "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])
}

可以吗?

5 个答案:

答案 0 :(得分:3)

您可以在Object.valuesmap()https://api.example.com/collection/all,这比循环更简洁,更容易阅读:

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)

答案 1 :(得分:2)

您可以使用Object.keysmap

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]));

答案 2 :(得分:0)

映射对象的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);

答案 3 :(得分:0)

尝试一下

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))

答案 4 :(得分:0)

您可以通过使用映射功能将Array.fromObject.values结合使用,以将每个对象映射到具有路径和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);