从js

时间:2015-07-02 06:36:37

标签: javascript

我有一个给定的exif of an image我想分割一个json对象的每个键并用它创建一个排序数组。我期待的输出是

{
  "APP14":[
    {"APP14Flags0": 16384},
    {"APP14Flags1": 0},
    {"ColorTransform": 1}
  ],
  "Composite":[
    {"Aperture": 2.8}
    {"CircleOfConfusion": 0.0309526315549036}
    {"DateTimeCreated":  "2013:08:04 13:15:03+00:00"}
    {"FocalLength35efl": 97.0717484087605}
    {"..."}
  ],
  "SourceFile": "c.jpg",
  "XMP":[
    {"AlreadyApplied": true},
    {"ApproximateFocusDistance": 1.17},
    {"AutoLateralCA": 0},
    {"Blacks2012": 0}
  ]
}

我的上一个console.log({key:values});给我回到同一个阵列。 js fiddle

var the_keys =[];
_.forEach(data, function(n, key) {
  //creating an array of Uniq keys
  if(key.indexOf(':')> -1) {
    if (_.includes(the_keys, key.split(':')[0] ) == false) {
      the_keys.push(key.split(':')[0]); 
    }
  } else {
    the_keys.push(key);
  }
});

console.log(the_keys);

_.forEach(the_keys, function(key) {
  var values = []
  _.forEach(data, function(k, n) {
    if ((_.includes(the_keys, key.split(':')[0] ) ) || k == key) {
      values.push(k);
    }
  });

  console.log({key:values});
});

我正在拆分每个键,因为我想创建一个类似于此exif viewer site

的HTML表格

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/L9a9h5m3/3/

看看这个。它基本上将键分开,然后逐块构建对象。对于最后一个标记,它分配值

_.forEach(data, function(v, k){
    kParts = k.split(':');

    var lastObj = returnObj;
    for(var i=0; i<kParts.length - 1; i++){
       var kPart = kParts[i]
       if(!lastObj.hasOwnProperty(kPart)) lastObj[kPart] = {}
       lastObj = lastObj[kPart];
   }

   lastObj[kParts[kParts.length - 1]] = v;

});

https://jsfiddle.net/L9a9h5m3/3/