-1

Say I have some JSON data like this:

blah = [
{"Species":"setosa","Sepal.Length":5.1,"Sepal.Width":3.5},{"Species":"setosa","Sepal.Length":4.9,"Sepal.Width":3}
]

In my code, I won't necessarily know the key names of the JSON. Therefore, I can grab the keys like this (I do know that all elements of the array are identical in their keys):

mynames = Object.keys(blah[0]); // gives this... ["Species", "Sepal.Length", "Sepal.Width"]

I am able to change the name of the first key called Species here to newthing like this:

JSON.parse(JSON.stringify(blah).split('"Species":').join('"newthing":'));

But if I didn't know it was called 'Species', but knew it was the first element of 'mynames', I thought I could do the same thing like this:

JSON.parse(JSON.stringify(blah).split('mynames[0]:').join('"newthing":'));

or

JSON.parse(JSON.stringify(blah).split('"mynames[0]":').join('"newthing":'));

but both fail. Is there a way of doing this simply?

jalapic
  • 13,792
  • 8
  • 57
  • 87
  • 1
    try `split('"' + mynames[0] + '":')` – Jaromanda X Dec 30 '16 at 01:29
  • @JaromandaX - of course, thanks. – jalapic Dec 30 '16 at 01:31
  • 1
    Turning structured data into a string to do this is silly, especially if you don't know the range of values in the JSON. What's to say a key's text might also exist in a value? It might work depending on the data but I think it's kludgy and fragile. – erik258 Dec 30 '16 at 01:31
  • Why not `.replace(mynames[0], "newthing")`? – RobG Dec 30 '16 at 01:32
  • @DanFarrell - thanks Dan, that's a very good point. In the very specific circumstances I need this for, the data will always be strings for keys and numeric values for values. However, I'd still rather use a more robust method. – jalapic Dec 30 '16 at 01:34
  • 1
    FYI, this is an array of objects, not JSON. JSON is a textual, language-indepdent data format. You have JavaScript. – Felix Kling Dec 30 '16 at 01:34
  • @FelixKling thanks Felix - good point. – jalapic Dec 30 '16 at 01:37

2 Answers2

1

It seems what you want is

blah[0].newthing = blah[0][mynames[0]];
delete blah[0][mynames[0]];

but knew it was the first element of 'mynames',

Note that the order of keys is not guaranteed, so that might not work in every environment or even for multiple runs.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

How do I remove a property from a JavaScript object? explains how the delete keyword can be used to remove properties. You can simply set the new property to the value of the old, then delete the old.

Community
  • 1
  • 1
erik258
  • 14,701
  • 2
  • 25
  • 31