简体   繁体   English

将未知路径的嵌套Json值推送到Javascript中的Array中

[英]Push nested Json Values with unknown path into Array in Javascript

So I don't know why Im struggling with this. 所以我不知道我为什么要为此苦苦挣扎。 It seems like I should be able to use Lodash or something to do this I would think. 我认为应该可以使用Lodash或其他方法执行此操作。

I have an object that looks like. 我有一个看起来像的物体。

  { "fdjkafdajkfasfjkdaslj": {
      "-LMUD-2APhiSLkEtVbM": {
        "profileName": "bob",
            "profilePic": "www.profilepic.com",
            "score": 73,
            "teamName": "lzs"
        }
    }
  }

I will not know the first to keys in the structure. 我不知道第一个要输入结构的键。 Example from above. 上面的例子。 "fdjkafdajkfasfjkdaslj" or "-LMUD-2APhiSLkEtVbM" . "fdjkafdajkfasfjkdaslj""-LMUD-2APhiSLkEtVbM"

I really just need to push these key values into an array. 我真的只需要将这些键值推入数组即可。

       "profileName": "bob",
        "profilePic": "www.profilepic.com",
        "score": 73,
        "teamName": "lzs"

What is the best way to accomplish this in javascript (im actually a React.js)? 用javascript(实际上是React.js)完成此操作的最佳方法是什么? I was thinking Lodash maybe but haven't found anything yet? 我在想Lodash,但还没有找到任何东西吗? Most of my searches for retrieving nested Key/Value data in Json indicate you would need a path but I will not have the path in this scenario. 我在Json中检索嵌套的键/值数据的大多数搜索都表明您需要一个路径,但在这种情况下我将没有该路径。 I won't know the top 2 keys in this object. 我不知道该对象的前2个键。 The only thing I have is this predicable object structure with 2 unknown keys before my key/value data. 我唯一拥有的是这个可预测的对象结构,在我的键/值数据之前有2个未知键。

If there will be only one key in object as in question sample then you can use Object.keys() 如果对象中只有一个键(如所讨论的示例),则可以使用Object.keys()

 const data = []; const obj = { "fdjkafdajkfasfjkdaslj" { "-LMUD-2APhiSLkEtVbM": { "profileName": "bob", "profilePic": "www.profilepic.com", "score": 73, "teamName": "lzs" } } }; const outerObj = obj[Object.keys(obj)[0]]; const item = outerObj[Object.keys(outerObj)[0]]; data.push(item); 

I think you'll want to use Object.values . 我认为您将要使用Object.values

const realData = Object.values( Object.values( weirdThing )[0] )[0]

yourArray.push(realData)

For JSON string, it can be found during parsing : 对于JSON字符串,可以在解析期间找到它:

 var obj, json = '{"fdjkafdajkfasfjkdaslj":{"-LMUD-2APhiSLkEtVbM":{"profileName":"bob","profilePic":"www.profilepic.com","score":73,"teamName":"lzs"}}}' JSON.parse(json, (k, v) => v.profileName ? obj = v : v) console.log( obj ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM