0

I am trying to achieve a data structure in javascript that looks like this:

settings: {
   { "key": "Language", "value": "en" },
   { "key": "Language", "value": "en" }
}

The amount of keys is variable and needs to be iterated over. I thought I could do it with an array but the [0] numbers are getting in the way.

This is what i have now:

convertSettingsToApiSaveFormat(values) {
        const keys = Object.keys(values);
        const items = Object.values(values);

        const valuesToSend = keys.map((key, i) => {
            return { key, value: items[i] };
        });
        return { settings: [valuesToSend] };
    }
}

Which returns: enter image description here

any help is much appreciated!

4
  • 6
    Expected output is not valid JavaScript. Commented Sep 5, 2019 at 10:00
  • What is the type of the parameter values? Commented Sep 5, 2019 at 10:02
  • You can't expect like this, In every javascript object {}, the key name is required to hold a value Commented Sep 5, 2019 at 10:03
  • 2
    Just remove the brackets: return {settings: valuesToSend} - it's already an array. Commented Sep 5, 2019 at 10:03

2 Answers 2

2

First of all this is an invalid data structure

settings: {
   { "key": "Language", "value": "en" },
   { "key": "Language", "value": "en" }
}

JavaScript object is bascally key value pair you can see the bellow two objects dont have and key.

Either it can be like this

 settings: {
   "someKey":  { "key": "Language", "value": "en" },
   "someKey2": { "key": "Language", "value": "en" }
}

or a simple JS array

settings: [
   { "key": "Language", "value": "en" },
   { "key": "Language", "value": "en" }
]
Sign up to request clarification or add additional context in comments.

Comments

1

You're placing valuesToSend inside an array - remove it, and you'll get your desired output*:

return { settings: valuesToSend };

* The result you currently want is invalid - this, however, is valid:

settings: [
  { "key": "Language", "value": "en" },
  { "key": "Language", "value": "en" }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.