-1

I have a json like this:

 [ {"numbers":["1","2","3","4"], 
    "city":"Tokio", 
    "color":"blue", 
   }, 

   {"numbers":["5","6","7","8"],
    "city":"Tokio",
     "color":"green", 
   }, 
    ......... 
 ]

and i need to convert to another json with javascript like this:

[ {"numbers":"1,2,3,4", 
    "city":"Tokio", 
    "color":"blue", 
   }, 

   {"numbers":"5,6,7,8",
    "city":"Tokio",
     "color":"blue", 
   }, 
    ......... 
 ]

so, i need to convert the array of numbers in a string, any idea? Thanks in advance.

guilieen
  • 150
  • 13

2 Answers2

2

For an array use this:

const jsonObjArray = [
  {
         "numbers":["1","2","3","4"],
         "city":"Tokio",
         "color":"blue"
  },
  {
         "numbers":["1","2","3","4"],
         "city":"New York",
         "color":"red"
  },
  {
         "numbers":["1","2","3","4"],
         "city":"Rome",
         "color":"green"
  }
]

const result = [];
jsonObjArray.map( item => {
  const numbers = item["numbers"];
  let numbersAsString = numbers.join(",");
  result.push({...item, numbers: numbersAsString});
});
    
console.log(result)
Ana Svitlica
  • 443
  • 2
  • 13
  • 1
    @AnaSvitlica Asker want to encode `JSON` after string conversion from array, your is incomplete please edit your answer to avoid downvotes. Thank you – Amaan warsi Sep 22 '20 at 12:47
1

Answer 1:

const data ={"numbers":["1","2","3","4"],
 "city":"Tokio",
 "color":"blue",
};
let modifyResult={}
for (const key in data) {
      if (data.hasOwnProperty(key)) {
      
      if(key==="numbers"){
      
      modifyResult[key]= data["numbers"].join(", ");
      
      }else{
      modifyResult[key]= data[key];
      }
        
        
      }
    }
    console.log("Final:",modifyResult);

Hope, this will solve your problem.

OutPut Screen-Shot:

enter image description here

Answer 2:

As per your comment you want to transform the array of object with their key, So I am providing Second answer

const data = [ {"numbers":["1","2","3","4"], "city":"Tokio", "color":"blue", }, {"numbers":["5","6","7","8"], "city":"Tokio", "color":"green", }];

const finalresult = data.map(item => {
    letcontainer = {};
    container = {...item};
    container.numbers = item.numbers.join(", ");

    return container;
})

console.log(finalresult);

OutPut Screen-shot:

enter image description here

Pramod Kharade
  • 2,005
  • 1
  • 22
  • 41
  • yes it works, but i forget that my json is an array also... i think is only add a for loop, but could be the best solution? this is mi json: [ {"numbers":["1","2","3","4"], "city":"Tokio", "color":"blue", }, {"numbers":["5","6","7","8"], "city":"Tokio", "color":"green", }, ......... ] – guilieen Sep 22 '20 at 12:37
  • In question, you have provide as object and here in comment array of object. you need to correct your question. – Pramod Kharade Sep 22 '20 at 12:42