Nikhil Bharadwaj
Nikhil Bharadwaj

Reputation: 917

Extract unique attributes from string in Javascript

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?

Upvotes: 0

Views: 53

Answers (1)

Kinglish
Kinglish

Reputation: 23654

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)

Upvotes: 2

Related Questions