Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Putting multiple values as single strings into object

I have an object values:

values = [{
    stringValues: "First value",
    kind: "stringValues"
  },
  {
    stringValues: "Second Value",
    kind: "stringValues"
  },
]

I need to extract the stringValues and put them into another object obj as a value to the key ghi. The final result should look like that:

{
  "name": "name",
  "abc": {
    "def": "def",
    "ghi": ["First Value", "Second Value"]
  }
}

My approach is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var valuesStr = "";
values.forEach(
  (v) => {
    valuesStr += `'${v.stringValues}',`
  }
);

obj = {
  name: "name",
  abc: {
    def: "def",
    ghi: valuesStr,
  },
};

But the result doesn’t look quite right:

{
  "name": "name",
  "abc": {
    "def": "def",
    "ghi": "'First value','Second Value',"
  }
}

As you can see, it puts both values as 1 string.

Fiddle: https://jsfiddle.net/zrx0sp76/

>Solution :

Well if you want it be an array, then declare it as an array and push() values to it.

var valuesArr = [];
values.forEach(
  (v) => {
    valuesArr.push(v.stringValues);
  }
);

obj = {
  name: "name",
  abc: {
    def: "def",
    ghi: valuesArr,
  },
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading