I was wanting to see if there is a relatively simple method for doing this as I can use the following:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var myobj = arr2.map(value => ({'Client': arr2[0], 'ActType': arr2[1], 'CallRepType': arr2[2]}));
But I get the same correct object 3 times in a row...I simply want a single object returned that looks like:
{Client: 'ECF', ActType: 'Meeting', CallRepType: 'Call Report'}
I know I can loop through both arrays but I was hoping to get a solution using map, reduce or taking advantage of spread in javascript...
A faster solution that uses Array.prototype.forEach():
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"]
var result = {};
arr.forEach((el, i) => { result[el] = arr2[i]; });
console.log(result);
Array.prototype.forEach()`
This a solution that uses Array.reduce() to create the object:
const arr = [ "Client", "ActType", "CallRepType"];
const arr2 = [ "ECF", "Meeting", "Call Report"]
const myobj = arr.reduce((r, key, i) => {
r[key] = arr2[i];
return r;
}, {});
console.log(myobj);
You can loop through the array and do it:
var arr = [ "Client", "ActType", "CallRepType"];
var arr2 = [ "ECF", "Meeting", "Call Report"];
var len = arr.length;
var myObj = {};
for (var i = 0; i < len; i++) {
var myObject = {};
myObj[arr[i]] = arr2[i]
// myObj.push = myObject;
}
console.log(myObj);
Related
I have this array:
myArray = ["AAA","BBB",...,"ZZZ"];
I want to convert it to an array of objects. Something like this:
myArray = [
{
"Id": "111",
"Value": "AAA"
},
....
{
"Id": "111",
"Value": "ZZZ"
},
];
I've tried to use the map method like this:
myArray.map(str => {
let obj = {};
obj['Id'] = '111';
obj['Value'] = str;
});
But console.log(myArray) outputs this:
undefined
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 need to return the result into a new variable, or your existing one, as map create a new array and doesn't change the one you are iterating over.
const myArrayOfObjects = myArray.map( str => {
let obj = {};
obj['Id'] = '111' ;
obj['Value'] = str ;
return obj;
});
I have two array. I want to merge this two arrays into one array. One array consisting keys and another one values.My array looks like
productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
"8": 5,
"7": 1,
"9": 3
}
I already tried to merge these arrays, in this way
var newArray = {};
for(var i=0; i< productId.length; i++){
newArray[productId[i]] = quantity [i];
}
console.log(newArray);
It returns
Object [ <7 empty slots>, "5", "1", "3" ]
You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object.
Please look here
Empty slots in JavaScript objects?
Try this
var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);
Try the following:
var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element
var obj = {};
var i = 0;
for(var k of productId) {
obj[k] = parseInt(quantity[i]);
i++;
}
console.log(obj);
Your new "array" is not an Array but an Object.
You can iterate on one of the arrays using Array.reduce to construct the object.
Something like that:
const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];
const result = arr1.reduce((obj, currentItem, index) => {
obj[currentItem] = arr2[index];
return obj;
}, {});
console.log(result);
I have the array ["oop", "poo", "oop", "kkd", "ddd", "kkd"].
Is there any elegant way I can split it to sub-arrays, so each array contains elements with same values?
I want to achieve the following
var arrayOne = ["oop", "oop"]
var arrayTwo = ["poo"]
var arrayThree = ["kkd", "kkd"]
var arrayFour = ["ddd"]
You could use reduce.
var arr = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
var mapped = arr.reduce((map, val)=>{
if(!map[val]) {
map[val]=[];
}
map[val].push(val);
return map;
}, {});
You can even get weird and make it a 1 liner, although probably not the brightest idea just in terms of clarity.
arr.reduce((m, v)=>(m[v]=m[v]||[]).push(v) && m, {});
You could maybe do something like this, but the requirement kinda feels like a code smell in the first place.
const mixedArray = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
const splitArrays = {};
mixedArray.forEach(v => {
if (!!splitArrays[v]) {
splitArrays[v].push(v);
} else {
splitArrays[v] = [v];
}
})
console.log(splitArrays);
edit: If functional purity is a concern then ug_'s use of reduce is ipso facto preferable.
You can create a dictionary counting the values:
counter = {}
L = myArray.length
for (var i = 0; i < L; i++)
{
if (myArray[i] in counter)
{
counter[myArray[i]]+=1
}
else
{
counter[myArray[i]]=1
}
}
You could reduce and destructure
var arr = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
var obj = arr.reduce( (a,b) => (a[b] = a[b] + 1 || 1, a), {});
var [arrayOne, arrayTwo, arrayThree, arrayFour] = Object.keys(obj).map(k=>Array(obj[k]).fill(k));
console.log(arrayOne, arrayTwo, arrayThree, arrayFour);
I am having an array of object in the below format:
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
}];
which I want to convert in a single object like:
var log={
"Name":"ABC",
"Department":"Computer"
};
I've tried the following approach:
for(var i=0;i<log.length;++i){
pushToAry(log[i].billkey, log[i].billvalue);
}
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
ary.push(obj);
}
But it will push a new object every time into the ary array, which results into:
var ary =[
0:{
"Name":"ABC"
},
1:{
"Department":"Computer"
}];
How could I convert this array of object into an object?
In ES6 this is quite clean:
let result = {};
for (let {billkey, billvalue} of log)
result[billkey] = billvalue;
or if you prefer "functional" style:
let result = Object.assign(...log.map(x => ( {[x.billkey]: x.billvalue} )))
You can use reduce() to return object.
var log = [{
billkey: "Name",
billvalue: "ABC"
}, {
billkey: "Department",
billvalue: "Computer"
}];
var result = log.reduce((r, e) => (r[e.billkey] = e.billvalue, r), {});
console.log(result)
If you just want to use a loop, you can do it like this :
var log = [
{
billkey: "Name",
billvalue: "ABC"
},
{
billkey: "Department",
billvalue: "Computer"
}];
var result = {};
log.forEach(x => result[x.billkey] = x.billvalue);
console.log(result);
You can use Array.prototype.reduce to reduce it to the required object - see demo below:
var log=[{billkey:"Name",billvalue:"ABC"},{ billkey:"Department",billvalue:"Computer"}];
var result = log.reduce(function(p,c){
p[c.billkey] = c.billvalue;
return p;
},{})
console.log(result);
var obj = {};
for (var i = 0; i < log.length; i++)
obj[log[i].billkey] = log[i].billvalue;
First, I prepare an empty object to store reult to. Then I go through the log and in every iteration, I extract the log record's key (log[i].billkey) and value (log[i].billvalue) and use it to add the new member to the result: obj[...key...] = ...value...;.
I have an array of objects like this:
[
{ "key": "fruit", "value": "apple" },
{ "key": "color", "value": "red" },
{ "key": "location", "value": "garden" }
]
I need to convert it to the following format:
[
{ "fruit": "apple" },
{ "color": "red" },
{ "location": "garden" }
]
How can this be done using JavaScript?
You can use .map
var data = [
{"key":"fruit","value":"apple"},
{"key":"color","value":"red"},
{"key":"location","value":"garden"}
];
var result = data.map(function (e) {
var element = {};
element[e.key] = e.value;
return element;
});
console.log(result);
also if you use ES2015 you can do it like this
var result = data.map((e) => {
return {[e.key]: e.value};
});
Example
Using an arrow function, with the data called arr
arr.map(e => {
var o = {};
o[e.key] = e.value;
return o;
});
This generates a new Array and does not modify the original
It can be simplified down to one line as
arr.map(e => ({[e.key]: e.value}));
If you can't assume arrow function support yet, you would write this longhand
arr.map(function (e) {
var o = {};
o[e.key] = e.value;
return o;
});
Using map (as suggested in other answers) or the following will do what you want...
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
var obj = {};
for(var i = 0; i < data.length; i++) {
obj[data[i]["key"]] = data[i]["value"];
}
In Javascript, obj.property and obj['property'] return same things.
obj['property'] is more flexible because the key 'property' could be a string with some space :
obj['pro per ty'] // work
obj.pro per ty // not work
or
var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true
So you could try that.
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];
var data_length = data.length; // just a little optimisation for-loop
for (var i = 0; i < data_length; i++) {
var item = data[i]; // to have a vision close of foreach-loop (foreach item of collection)
new_data[i] = {};
new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]
What you currently have is an array of object, each having two attributes, key and value. If you are not aware of map, you can always run a forEach loop on this array and rearrange the data. Try something like below:
function() {
var newArray = [];
oldArray.forEach(function(x){
var obj= {};
obj[x.key] = x.value;
newArray.push(obj);
});
console.log(newArray);
}
here oldArray is your original data