JS : Convert Array of Strings to Array of Objects
You can use .map()
for this. It passes the index into the callback.
myArray = myArray.map((str, index) => ({ value: str, id: index + 1 }));
Convert array of strings into an array of objects
Another approach - Array#reduce
.
var arr = ["124857202", "500255104", "78573M104"];var res = arr.reduce(function(s, a){ s.push({name: a}); return s; }, []) console.log(res);
Convert array of string into array of object with different keys JS
If you only have one array containing one set of data there's no need to use map
. Destructure the array elements, and then just create a new object using those variables.
const arr = [ '612772d3d8b2b2000482fc3c', '15', '15', 'Basketball', '2021' ];
const [ id, amount, bet, sport, date ] = arr;
const obj = [ { id, amount, bet, sport, date } ];
console.log(obj);
Convert Array to Object
ECMAScript 6 introduces the easily polyfillable Object.assign
:
The
Object.assign()
method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
For custom keys you can use reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
Convert array of strings into an array of objects in javascript?
You can use array#map
to modify each string of the original array, and string#split
to break each string into it's key: value
pairs.
Full code:
let arr = [
"test: Yes, name: user1, number: +9190000000",
"test: Yes, name: user2, number: +9162000000",
];
arr = arr.map((objStr) => {
let object = {};
objStr.split(",").forEach((pair) => {
let [key, value] = pair.split(":");
object[key.trim()] = value.trim();
});
return object;
});
console.log(arr);
How to convert an Array to Array of Object in Javascript
Try the "map" function from the array:
const output = [ 'John', 'Jane' ].map(name => ({name}));console.log(output);
How to convert an Array to Array of objects with same keys in Javascript?
You can do this using Array.map
, which allows you to specify a function that returns a new item to replace in the array.
arr.map(o => ({ name: o }))
Here's one without fancy arrow function shorthand, just in case you are confused.
arr.map(function(o) {
return {
name: o,
}
})
How to convert an array of type String to an array object in javascript
What you have here is a JSON string. You can parse it to get the object / array:
var array = JSON.parse(arrayString)
Edit: I see your JSON string has single quotes. You need to replace all of them with double quotes before parsing:
JSON.parse(arrayString.replace(/'/g, '"'))
Function to convert array of strings into array of objects
Change the following line :
o.key = array[i]
//change
o[key] = array[i]
function arrayToObjects(array, key) {
const objectArray = []; // To return an array later.
this.key = key;
for (const element of array) {
const o = new Object();
o[key] = element;
objectArray.push(o);
}
return objectArray;
}
Convert array of objects to array of strings in mongodb
It seems that I was over complicating this. I was able to achieve my desired result by doing the following:
db.classes.aggregate( [
{
$lookup:
{
from: "members",
localField: "enrollmentlist",
foreignField: "name",
as: "enrollee_info"
}
},
{
$project:
{
"_id": 1,
"title": 1,
"days": 1,
"enrollee_names": "$enrollee_info.name"
}
}
] )
Result:
[
{
"id": 1,
"title": "Reading is ...",
"days": [
"M",
"W",
"F"
],
"names": [
"artie",
"pandabear",
"giraffe2"
]
},
{
"id": 2,
"title": "But Writing ...",
"days": [
"T",
"F"
],
"names": [
"artie",
"giraffe1"
]
}
]
Related Topics
JavaScript Associative Array to JSON
How to Get Evaluated Attributes Inside a Custom Directive
Preventdefault() on an <A> Tag
"Object Doesn't Support This Property or Method" Ie10/11
React-Router: No Not Found Route
Document.All VS. Document.Getelementbyid
Should I Be Using Object Literals or Constructor Functions
How to Refresh an Iframe Using JavaScript
Why am I Getting a Referenceerror: Abortcontroller Is Not Defined in Discord.Js V13
Using _ (Underscore) Variable with Arrow Functions in Es6/Typescript
Scrolling an Iframe with JavaScript
How Can Jquery Deferred Be Used
How to Get Selected HTML Text with JavaScript
Differencebetween Bower and Npm
Immediate Function Invocation Syntax
Onclick Not Working on Mobile (Touch)