如何过滤javascript对象并获得所需的输出作为数组?

时间:2017-07-07 09:54:35

标签: javascript ecmascript-6

[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }  
]

所需输出= [“A”,“B”,“D”];

2 个答案:

答案 0 :(得分:0)

var obj=[
         {imgUrl: "A"},
         {imgUrl: "B"},
         {imgUrl: "C", file: {fileName: "D"} }  
       ];
    var y=obj.map(function(z)
     {

      if(typeof(z.file) !== 'undefined')
       {
         return z.file.fileName;

       }
       else
       {
          return z.imgUrl;
       }
     });

 y is your desired array.

答案 1 :(得分:0)

使用Array.prototype.map()和某些条件来处理您的要求。

array.map((value) => {
  if (value.file && value.file.fileName) {
    return value.file.fileName;
  }

  return value.imgUrl;
});