I am using Object.assign method to change the structure of my JSON.
let opVal = []
data[item].map(function(key,value) {
opAllVal = key;
finalResult = Object.assign(data, {[item]: [opAllVal]});
});
Here data
contains the JSON. And key
contains more than one value at a time. I want to send all the values that are coming in key
in the below format. For eg, If item
is sampleKey
and values in key
are sampleValue1
and sampleValue2
, so they should be sent as -
"sampleKey":["sampleValue1","sampleValue2"]
but with the above code, these are sending as -
"sampleKey":["sampleValue2"]
Only the last value is getting sent everytime, not all the values which are coming in key
. Can anyone help me in sending all the values of key
to item
in the above format.
Thanks in advance...
Every time you use the code finalResult = Object.assign(data, {[item]: [opAllVal]});
, you are overwriting the previous version of data[item]
ignoring the previous content, in other words, data[item]
is always set to an array with a single element that is key
.
Btw, by the code it's not very clear what you'd like to do. If I understood you can have an input like this:
data = {
... //other params
"sampleKey": [
"sampleValue1",
"sampleValue2"
]
}
What's the expected output?
For what I see in the code it will be better to use forEach
instead of map
and the name of the variables in forEach should be inverted (value, key)
instead of (key, value)
as map
and forEach
call both the callback by passing before the value and after the key.
Also I suggest to change the tag in your question as it is not related to reactjs
but it's related to js and independent from react (if you do this you'll receive more visualisations and more answers).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.