-5

For Example:

var arr = ["tag1, tag2"]

I want to have the above array in JSON format as follows:

var arr = [
    {"name": "tag1"},
    {"name": "tag2"}
]

Can someone please help me out to solve this problem.

Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
  • That is not "JSON format". Recommended reading: https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation – JJJ Mar 19 '18 at 10:09

4 Answers4

0

This should work:

var arr = ["tag1", "tag2"];
var json= [];
arr.forEach(e => json.push({name:e}));
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

You input array should be like, Then you can use array.map to iterate over objects and create new objects

var arr = ["tag1", "tag2"]

DEMO

var arr = ["tag1", "tag2"];

var  newList = arr.map(v => {
  return Object.assign({}, { Name: v })
});
console.log(newList);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

you could also do this on your array using map function:

var objArray = ["tag1", "tag2"].map(el => {
  return { name: el };
});
console.log(objArray);

if your problem is having 2 different arrays as you mentioned in a comment above & you want to remove duplicate tags, you could do this:

var l1 = [
  {'id': 2,'name':'tag1'}, 
  {'id': 3, 'name':'tag2'}, 
  {'id': 4, 'name':'tag3'}];

var l2 = [ "tag5", "tag2", "tag3", "tag6" ];

l2 = l2.map(el => {
  return { name: el };
});

// concat both the arrays
var src = l1.concat(l2);

// remove duplicates
var temp = [];
const unique = src.filter(item => {
  if (temp.indexOf(item.name) === -1) {
    temp.push(item.name);
    return item;
  }
});
console.log(unique);
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
-2
var obj = { "name":"John", "age":30, "city":"New York"};

var myJSON = JSON.stringify(obj);

thats it...!

Jay Patel
  • 305
  • 2
  • 6
  • 20