在JSON中查找特定值的多个ocncences

时间:2018-06-13 14:42:48

标签: javascript json

我有一个像这样的复杂JSON:

{
  "a": {
    "b": {
      "c": {
        "price": {
          "type": "coin",
          "value": "currency"
        }
      }
    }
  },
  "e": {
    "f": {
      "price": {
        "type": "note",
        "value": "currency"
      }
    }
  },
  "price": {
    "type": "cents",
    "value": "dollars"
  }
}

我正在尝试编写一个JavaScript函数,它会找到" price"在任何地方,拔出"类型"和"价值"为了它。所以我的输出应该是:

"coin" : "currency"
"note" : "currency"
"cents" : "dollars"

4 个答案:

答案 0 :(得分:3)

您可以使用### Import necessary packages import matplotlib.pyplot as plt import pandas as pd import matplotlib.dates as mdates # For formatting dates ### Make the figure fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(15, 4.18)) # Original plot ax[0].plot(df["Date"][:322], df["Concentration"][:322], "+", color="red", linewidth=0.5) ax[0].set_title('Original plot') # New xticks plot months = mdates.MonthLocator() # Add tick every month days = mdates.DayLocator(range(1,32,5)) # Add tick every 5th day in a month monthFmt = mdates.DateFormatter('%b') # Use abbreviated month name # Add the locators to the axis ax[1].xaxis.set_major_locator(months) ax[1].xaxis.set_major_formatter(monthFmt) ax[1].xaxis.set_minor_locator(days) # Plot ax[1].plot(df["Date"][:322], df["Concentration"][:322], "+", color="red", linewidth=0.5) ax[1].set_title('Updated xticks') plt.show() 循环创建递归函数以返回对象作为结果。

for...in

答案 1 :(得分:3)

您可以检查所需的密钥price并将typevalue用于新对象,或者查看更深的内容。

function flat(object) {
    return Object.entries(object).reduce(
        (r, [k, v]) => Object.assign(r, k === 'price' ? { [v.type]: v.value } : flat(v)),
        {}
    );
}

var object = { a: { b: { c: { price: { type: "coin", value: "currency" } } } }, e: { f: { price: { type: "note", value: "currency" } } }, price: { type: "cents", value: "dollars" } };

console.log(flat(object));

答案 2 :(得分:1)

您需要递归(或不)迭代对象的属性。 这是一些老式的javascript:



const testObj =  {
    "a":{
        "b" : {
            "c" :{
                "price" : {
                    "type" : "coin",
                    "value" : "currency"
                }
            }
        }
    },
    "e" : {
        "f" : {
            "price" : {
                "type" : "note",
                "value": "currency"
            }
        }
    },
    "price": {
        "type": "cents",
        "value": "dollars"
    }
};

function findOccurences(accum, obj, prop) {
  if(obj.hasOwnProperty(prop)) {
     accum.push(obj[prop]);
  }
  for(var p in obj) {
    if(obj.hasOwnProperty(p) && p !== prop)
      findOccurences(accum, obj[p], prop);
  }
}
var accum = [];
findOccurences(accum, testObj, "price");
console.log(accum);




答案 3 :(得分:1)

虽然其他答案都很好,但他们不允许对同一个键使用不同的值。例如,如果您有这样的额外价格:

"g": {
  "price": {
    "type": "coin",
    "value": "dollars"
  }
}

它将使用其他答案覆盖coin的第一个值,您将最终得到:

{
  "coin": "dollars",
  "note": "currency",
  "cents": "dollars"
}

如果您有这种情况并希望获得coin的两个不同值,则您需要为每个键/值使用单独的对象,而不是使它们成为单个对象的属性:< / p>

&#13;
&#13;
var json = {
  "a": {
    "b": {
      "c": {
        "price": {
          "type": "coin",
          "value": "currency"
        }
      }
    }
  },
  "e": {
    "f": {
      "price": {
        "type": "note",
        "value": "currency"
      }
    }
  },
  "price": {
    "type": "cents",
    "value": "dollars"
  },
  "g": {
    "price": {
      "type": "coin",
      "value": "dollars"
    }
  }
};

function getPrice(data) {
  var result = [];
  for (let i in data) {
    if (i == "price")
      result.push({
        [data[i].type]: data[i].value
      });
    else if (typeof data[i] == "object")
      result.push(getPrice(data[i])[0]);
  }
  return result;
}

var price = getPrice(json);
console.log(price)
&#13;
&#13;
&#13;