This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings into an array of objects
(6 answers)
Closed 3 years ago.
What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
You can use .map() to get the desired output:
const data = ['firstName','lastName','gender'];
const result = data.map(name => ({ title: name }));
console.log(result);
Try this code.I hope it will helps you.
var arr = ['firstName','lastName','gender']
var jsonObj = {};
for (var i = 0 ; i < arr.length; i++) {
jsonObj['title' +(i+1) ] = arr[i];
}
console.log(jsonObj)
You can simply use forEach() loop which is the easiest way:
var arr = ['firstName','lastName','gender'];
let res = [];
arr.forEach((item) => res.push({title: item}));
console.log(res);
Just to build your knowledge in Array operations you can also use reduce():
var arr = ['firstName','lastName','gender'];
let res = arr.reduce((acc, item) => {
acc.push({title: item});
return acc;
}, []);
console.log(res);
Related
This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like
This question already has answers here:
How to add index values of array in object to a key
(7 answers)
Closed 4 months ago.
I've a data like this.
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
]
arr.forEach((v,i,a)=>{
console.log(v)
})
And I want to transfer to
arr = [{id:1,name:john},{id:2,name:jeff},{id:3,name:bob},{id:4,name:peter}]
I want to add id to every object in array.
How to solves this, Thank you.
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
]
arr.forEach((v,i,a)=>{
v.id = i + 1
})
console.log(arr)
Try this :
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
];
const res = arr.map((obj, index) => {
return {
...obj,
id: index + 1
}
});
console.log(res);
This question already has answers here:
How to add prefix to array values?
(5 answers)
Closed 4 years ago.
Input: The Array of the strings
var arr = ['a','b','c'];
var prefix = 'prefix_';
Output: Each element in the array should be prefixed by 'prefix':
['prefix_a','prefix_b','prefix_c']
You just need to use Array.prototype.map here, it transforms each element of the array based on the callback method.
var arr = ['a','b','c'];
var prefix = 'prefix_';
var newArr = arr.map(el => prefix + el);
console.log(newArr);
A simpler, ES6 way using Array#map :
const prefixArray = (array, prefix) => array.map(e => prefix+e);
Demo:
let arr = ['a','b','c'];
const prefix = 'prefix_';
const prefixArray = (array, prefix) => array.map(e => prefix+e);
console.log(prefixArray(arr,prefix));
This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
DashboardService.GetDateList($scope.datestart, $scope.dateend).then(function (response) {
$scope.listdate = response.data;
});
i get an array list from this function above
[{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}
how can i push all day value from this array into a new one.
You can use Array#map to get the value of every day key.
var arr = [{"day":1,"sql_date":"2017-04-01T00:00:00"},{"day":2,"sql_date":"2017-04-02T00:00:00"},{"day":3,"sql_date":"2017-04-03T00:00:00"},{"day":4,"sql_date":"2017-04-04T00:00:00"},{"day":5,"sql_date":"2017-04-05T00:00:00"}],
newArr = arr.map(v => v.day);
console.log(newArr);
You can achieve this in different ways :
Using JavaScript for...in loop.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = [];
for (var i in responseObj) {
newArr.push({"day":responseObj[i].day});
}
console.log(newArr);
Using Array map() method.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = responseObj.map(function(item) {
return {"day":item.day};
});
console.log(newArr);
Using JavaScript for loop.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = [];
for (var i = 0; i < responseObj.length; i++) {
newArr.push({"day": responseObj[i].day});
}
console.log(newArr);
Still you can use map instead of for loop. Please find the code snippet below
var arr = [{"day":1,"sql_date":"2017-04-01T00:00:00"},{"day":2,"sql_date":"2017-04-02T00:00:00"},{"day":3,"sql_date":"2017-04-03T00:00:00"},{"day":4,"sql_date":"2017-04-04T00:00:00"},{"day":5,"sql_date":"2017-04-05T00:00:00"}],
newArr = arr.map(function(obj) { return obj.day });
console.log(newArr);