如何从Angular中的动态键对值获取数据

时间:2019-02-11 09:28:05

标签: javascript json angular typescript

这是我的问题,我无法从动态json获取动态密钥对值 下面是我的json

var d =   {
      "pexels-photo.jpeg": {
        "information": "laptop",
        "desc": {
          "mimetype": "image/jpeg",
          "id": "shsj44",
          "file_id": "pexels-photo.jpeg"
        },
        "_id": "shsj44"
      }
    }

我在下面尝试过

Object.keys(d).forEach(function(key){
    var value = d[key];
     console.log(key + ':' + value) ;
});

我想获取id值“ _id”和“ file_id”值

4 个答案:

答案 0 :(得分:2)

您可以使用 Destructuring assignment

var d = {"dynamic": {"information": "laptop","desc": { "mimetype": "image/jpeg","id": "shsj44","file_id": "pexels-photo.jpeg" },"_id": "shsj44"}}
 
let dynamicKey = Object.keys(d)[0]
let {[dynamicKey]:{desc:{
  file_id
},_id}} = d

console.log(file_id, '\n', _id)

答案 1 :(得分:1)

这是因为+之前的value,它将尝试连接该值,并且您会看到[object object]

var d = {
  "pexels-photo.jpeg": {
    "information": "laptop",
    "desc": {
      "mimetype": "image/jpeg",
      "id": "shsj44",
      "file_id": "pexels-photo.jpeg"
    },
    "_id": "shsj44"
  }
}


Object.keys(d).forEach(function(key) {
  let value = d[key];
  console.log(key + ' : ', value);
  console.log(key + ' : ', value.desc.id);
});

答案 2 :(得分:1)

您需要检查该值是否为object,如果是,则需要再次遍历。

以下代码将打印d中的每个键值对

export class AppComponent implements OnInit {
  d = {
    'pexels-photo.jpeg': {
      'information': 'laptop',
      'desc': {
        'mimetype': 'image/jpeg',
        'id': 'shsj44',
        'file_id': 'pexels-photo.jpeg'
      },
      '_id': 'shsj44'
    }
  };

  ngOnInit(): void {
    this.calc(this.d);
  }

  calc(val) {
    Object.keys(val).forEach(key => {
      const value = val[key];
      if (typeof (value) === 'object') {
        this.calc(value);
      } else {
        console.log(key + ':' + value);
      }
    });
  }

}

答案 3 :(得分:1)

尝试一下:

var d = {
      "pexels-photo.jpeg": {
        "information": "laptop",
        "desc": {
          "mimetype": "image/jpeg",
          "id": "shsj44",
          "file_id": "pexels-photo.jpeg"
        },
        "_id": "shsj44"
      }
    };
    
Object.keys(d).filter(key => {
    	Object.keys(d[key]).filter(item => {
        if (item === 'desc') {
        	Object.keys(d[key][item]).filter(elem => {
            if ((elem === 'id') || (elem === 'file_id')) {
              console.log(elem + ' : ' + d[key][item][elem]);
            }
          });
        }
      })
});