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?

4
  • If json[username] works then json is an object and not JSON -> What is the difference between JSON and Object Literal Notation? Commented Mar 7, 2020 at 17:29
  • You can't have a key outside an object. Commented Mar 7, 2020 at 17:30
  • Your output makes no sense, key: value on its own doesn't mean anything (it's a label). Why not create an object that also includes the key, for example? Commented Mar 7, 2020 at 17:30
  • Please add a minimal reproducible example 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). Commented Mar 7, 2020 at 17:32

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

-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?

5 Comments

That is a good way to get the key; but data still console logs as {"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}
need: {"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
I just tried to hardcode it and the object stops reporting: userA = "{" + username + ":"+json[username]+"}";
try: console.dir(data); - where data is the json data.
what about: userA = ' "{" + username + ":"+json[username]+"}" '

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.