-1

I have an array or may be payload which is object an array,

{
    "key": "value",
    "key2": "value2"
    "myids": [
        {
            "key": "value",
            "num": 123,
            "label": "equal"
        }
    ]
}

but need to change this payload to just below object of object

{
    "key": "value",
    "key2": "value2"
     "myids": {
        "myid": {
            "key": "value",
            "num": 123,
            "value": "equal"
        }
    }
}

this myid object is fix i have to make this and put array into this any kind of help of would be grateful...

user16821057
  • 59
  • 2
  • 9
  • That isn't JSON. It's a Javascript object. JSON is the string representation of a Javascript object. – Lee Taylor Jun 17 '22 at 00:33
  • Where does `myid` come from? What if the array is empty? What if there is more than one value in the array? – Bergi Jun 17 '22 at 00:41
  • @Bergi myid is sub object of myids and it must have value but value can be change some time might be 3 or some time might be 4 – user16821057 Jun 17 '22 at 02:10

2 Answers2

2

The simplest way would probably be to just create a new object and use the spread operator to copy the object and overwrite the myids array.

const obj = {
    "key": "value",
    "key2": "value2",
    "myids": [
        {
            "key": "value",
            "num": 123,
            "label": "equal"
        }
    ]
}

const newObj = { 
    ...obj,
  "myids": {
    "myid": obj.myids[0]
  }
}

Of course, this isn't very dynamic, but it does the trick. If you have more than one element in the array you could use a loop - but you would also need to have different names for the new object.

Bjorno
  • 291
  • 2
  • 12
0

you can make it in one line:

data.myids = { myid:data.myids[0] };
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Serge
  • 40,935
  • 4
  • 18
  • 45