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.
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.
This should work:
var arr = ["tag1", "tag2"];
var json= [];
arr.forEach(e => json.push({name:e}));
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);
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);
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
thats it...!