How can i edit an array inside an object?
My array contains a string, but i wanted the string to be split up via .split("") or another method.
This is how it looks at the moment:
line1_x = [
{"id": 1, "topic_no": 451, "keywords": ["[Keyword1, Keyword2, Keyword3]"] },
{"id": 2, "topic_no": 452, "keywords": ["[Keyword1, Keyword2, Keyword3]"] },
{"id": 3, "topic_no": 453, "keywords": ["[Keyword1, Keyword2, Keyword3]"] }
]
In this case, the brackets are part of the string. I would remove them via .replaceAll() or regex, i guess?
What i would like to archieve is following:
line1_x = [
{"id": 1, "topic_no": 451, "keywords": ["Keyword1", "Keyword2", "Keyword3"] },
{"id": 2, "topic_no": 452, "keywords": ["Keyword1", "Keyword2", "Keyword3"] },
{"id": 3, "topic_no": 453, "keywords": ["Keyword1", "Keyword2", "Keyword3"] }
]
I assume i need to iterate through the line1_x via a normal loop and use the .split("") method?
4
Answers
To edit the arrays inside the objects and split the strings into separate keywords, you can loop through the array and use the map function to update the keywords property. Here’s a step-by-step explanation of how you can achieve this in JavaScript:
Here is a simple solution. Note that I came to the conclusion that your
keywords
will always have one member.I propose a regex solution:
If your keywords consist of alphanumeric chars only you could use a simple regex
/w+/g
to match all keywords. Also note that using rest syntax involves iterators which are slow, so if the object structure is known and performance is important I suggest to compose object manually.Also it’s not clear whether you want to get a new array or modify the existing one.
To create a new array (pure approach):
And the benchmark: