JavaScript String Array to Object

Javascript string array to object

Super simple Array.prototype.map() job

names.map(name => ({ name }))

That is... map each entry (name) to an object with key "name" and value name.

var names = [    "Bob",    "Michael",    "Lanny"];
console.info(names.map(name => ({ name })))

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" }

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, '"'))

Convert string Array to Object Array in javascript

Use Array.map()

const a1 = [1,2,3];
const b1 = a1.map(val => ({id: val}));
console.log(b1);

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);

In javascript, how to convert string array into array of object?

You can use Array.map():

var languages = ["Arabic", "Irish"];var res = languages.map(item => ({'value':item, 'label':item}));console.log(res);

How do I convert a javascript object array to a string array of the object attribute I want?

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);

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 }));

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,
}
})


Related Topics



Leave a reply



Submit