You can use .map() for this. It passes the index into the callback.
myArray = myArray.map((str, index) => ({ value: str, id: index + 1 }));
Answer from Pointy on Stack Overflowjavascript - Convert array of strings into an array of objects - Stack Overflow
How can I convert an array of strings to an array of objects in JavaScript? - Stack Overflow
node.js - How can I convert string to array of objects in JavaScript - Stack Overflow
jquery - Best way to convert string to array of object in javascript? - Stack Overflow
Use Array#map to convert each value into a different value:
var newArr = arr.map(function(value) {
return {name: value};
});
Array#map applies the callback to each element in the array and returns a new array containing the return values of the callback.
I would take a look at the array.map function in javascript.
const mappedArr = arr.map(value => {
return {
name: value
}
})
You need to return a result from the mapper function.
let myNewArray = myArray.map( str => {
let obj = {};
obj['Id'] = '111' ;
obj['Value'] = str ;
return obj;
});
// or
let myNewArray = myArray.map( str => ({Id:111,Value:str}) );
// parenthesis are needed to remove the ambiguity with `{}`
console.log(myNewArray);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Using_map_to_reformat_objects_in_an_array
Here is the clean ES6 one liner version using Array#map
const data = myArray = ["AAA","BBB","ZZZ"];
let result = data.map(e => ({'Id': '111', 'Value': e}));
console.log(result);
You could split and iterate the array.
const
string = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true',
result = [];
for (let i = 0, a = string.split('|'); i < a.length; i += 2) {
const
option = a[i],
value = JSON.parse(a[i + 1]);
result.push({ option, value });
}
console.log(result);
You can use .match() on the string with a regular expression to get an array of the form:
[["Option 1", "false"], ...]
And then map each key-value into an object like so:
const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const res = str.match(/[^\|]+\|[^\|]+/g).map(
s => (([option, value]) => ({option, value: value==="true"}))(s.split('|'))
);
console.log(res);
I think that the best way of doing this, as Douglas Crockford (one of the biggests gurus of JavaScript) suggests in here is using the JSON native parser, as it is not only faster than the eval(), it's also more secure.
Native JSON parser is already available in:
- Firefox 3.5+
- IE 8+
- Opera 10.5+
- Safari Safari 4.0.3+
- Chrome (don't know which version)
And Crockford has made a safe fallback in javascript, called json2.js, which is an adaption of the eval() approach, with some security bits added and with the native JSON parsers API. You just need to include that file, remove its first line, and use the native JSON parser, and if it's not present json2 would do the work.
Here is an example:
var myJSONString = '{ "a": 1, "b": 2 }',
myObject = JSON.parse(myJSONString);
Once parsed you'll get an object with attributes a and b, and as you may know, you can treat an object as a hash table or associative array in JavaScript, so you would be able to access the values like this:
myObject['a'];
If you just want a simple array and not an associative one you could do something like:
var myArray = [];
for(var i in myObject) {
myArray.push(myObject[i]);
}
Lastly, although not necessary in plain JavaScript, the JSON spec requires double quoting the key of the members. So the navite parser won't work without it. If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" ); approach.
Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.
function malformedJSON2Array (tar) {
var arr = [];
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
arr[i] = {};
pair = cur.split(':');
arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return arr;
}
malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]
That code will turn your string into an Array of Objects (plural).
If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:
function malformedJSON2Object(tar) {
var obj = {};
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
pair = cur.split(':');
obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return obj;
}
malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}
The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.
Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.
<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>
I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.
Try to use array.prototype.map to ease your work,
var newArray = arr.map(function(str){
return JSON.parse("{" + str.substring(0,str.length - 1).replace(/lat/,'"lat"').replace(/lng/,'"lng"') + "}")
});
As well as, if you have the string in that array in a proper format, then some unnecessary .replace() can be removed which will results in performance boost.
DEMO
You can do this:
<!DOCTYPE html>
<html>
<body>
<script>
var data = ["lat: 0, lng: 0;", "lat: 25.233, lng:22.455;"];
var newData = new Array();
for(var i = 0; i < data.length; i++)
{
var temp = data[i].replace(/lat/g, "\"lat\"");
temp = temp.replace(/lng/g, "\"lng\"");
temp = temp.replace(/;/g, "");
temp = "{" + temp + "}";
newData.push(JSON.parse(temp));
}
console.log(newData);
</script>
</body>
</html>
Use map when you want to create a new array from a source one by modifying it's values.
var arrayOfObjects = data.map(function (item) {
return { item: item };
});
Two ways:
var arrOfStrs = ["1","2","3","4"];
// first way - using the regular for
var arrObj1 = [];
for(var i = 0 ; i < arrOfStrs.length; i++)
{
arrObj1.push({item: arrOfStrs[i]});
}
console.log(arrObj1);
// second way - using for...in
var arrObj2 = [];
for(var key in arrOfStrs)
{
arrObj2.push({item: arrOfStrs[key]});
}
console.log(arrObj2);
JSFIDDLE.
If your array of objects is items, you can do:
var items = [{
id: 1,
name: 'john'
}, {
id: 2,
name: 'jane'
}, {
id: 2000,
name: 'zack'
}];
var names = items.map(function(item) {
return item['name'];
});
console.log(names);
console.log(items);
Documentation: map()
Use the map() function native on JavaScript arrays:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});