0

I am filtering data that looks like below with json[username] for example.

data looks like:

{"albert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"petey":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"gilbert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}

so, for instance json[sally] brings in sally data but omits her name (the key) giving me the below:

{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}

I need to bring in/keep the name key as well. i.e. the whole line:

{"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}

If I hardcode it: user = "{" + username + ":"+json[username]+"}"; the object stops working: consoles as just {sally:[object Object]}. Anyway to achieve this?

Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • If `json[username]` works then `json` is an object and not [JSON](https://www.json.org/json-en.html) -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Mar 07 '20 at 17:29
  • You can't have a key outside an object. – Barmar Mar 07 '20 at 17:30
  • Your output makes no sense, `key: value` on its own doesn't mean anything (it's a [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label)). Why not create an object that *also* includes the key, for example? – jonrsharpe Mar 07 '20 at 17:30
  • Please add a [mcve] that shows what you've tried so far and the actual (but stripped down) input and output format. Right now this question doesn't make much sense (imho). – Andreas Mar 07 '20 at 17:32

2 Answers2

1

You can loop over the json and try it in this way,

for(let item in json){
    let data = {};
    data[item] = json[item];
    console.log(data);
}
Anurodh Singh
  • 814
  • 5
  • 9
-1

You can simply loop over the data like so:

for(var key in data){
    console.log(key);
    console.log(data[key]);
}

here, key will store the name sally, while data stored in sally is extracted via data[key].

You can also refer this post: How to loop through key/value object in Javascript?

Ayush Mandowara
  • 490
  • 5
  • 18