0

We have a string which I use for filter query. We need to extract the unique attribute keys from the string(For ex: z5,l3,d) from the below string. I'm trying to convert it to JSON format and extract it by using JSON.parse(). But it takes only the first object.

Is there any better way to achieve it?

let initialString = ""$or":[{"z5":"NEW"},{"z5":"OLD"}],"$or":[{"l3":"8125"}],"$or":[{"d":"20982056"}]"
let filteredString = initialString .replace(/[&\/\\#+()$~%.'*?<>]/g, '')
let finalString = `{"${filteredString .replace(/\\/g, '').substring(1, filteredString .length)}}`;
let jsonString= JSON.parse(finalString );

How can I get the attribute keys(z5,l3,d) from the string?

1 Answer 1

2

I wasn't sure if you wanted just an array of keys, or just the objects with those keys, so here both are...

let initialString = `""$or":[{"z5":"NEW"},{"z5":"OLD"}],"$or":[{"l3":"8125"}],"$or":[{"d":"20982056"}]"`

let finalJSON = [...initialString.match(/{(.*?)}/g, '')]
console.log(finalJSON)
console.log(finalJSON[1])

let keyArray = [... new Set(initialString.match(/{(.*?)}/g, '').map(e=>e.replace(/"/g,'')).map(e => e.split(":")[0].slice(1)))];
console.log(keyArray)

Sign up to request clarification or add additional context in comments.

1 Comment

Just wanted the array of keys. Thanks for sharing both the solutions. This is simple and easy to use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.