Home > OS >  Convert JSON response
Convert JSON response

Time:09-09

How do I convert below data to A-Apple, B-Apple, A-Mango

{
        "Apple": [
            "A",
            "B"
        ],                                         
        "Mango": [
            "A"
        ]
    }

CodePudding user response:

can you please explain what you want to achieve and not just ask for a solution? However, you can use Object.entries to loop through and get [key, value] and loop through again to get the desired result.

Does the result have to be a string or array?

See the example below.

const array = {"Apple": ["A","B"],"Mango": ["A"]};
let results = [];


//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
for (const [key, value] of Object.entries(array)) {
  // Get values for the key and iterate
  var values = (value || "").toString().split(",");
  // Iterate through values and append Key as desired
  (values || []).forEach(val => {
      results.push(`${val}-${key}`);
  });
};

const asArr = results;
const asString = results.join(', ');

console.log(`As ${typeof asArr}: `   asArr);
console.log(`As ${typeof asString}: `   asString);

  • Related