Combine Array(s) into single object in JavaScript - javascript

Currently I have 3 arrays:
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
I would like to merge all the array into one object instead and I tried using for loop but got an error instead:
var finalObj = {};
for (var y = 0; y < dateArray.length; y++) {
finalObj[y].id = idArray[y];
finalObj[y].date = dateArrayArrange[y];
finalObj[y].content = contentArray[y];
}
The end result I want to achieve:
finalObj = [{id:13, date:20181920, content:"content1"},
{id:24, date:20181120, content:"content2"},
{id:35, date:20172505, content:"content3"}];

finalObj is an object you need to push the value in an array.Beside you can also use array map method which will return an array so there is no need to separately push the values to an array.
Use map method on any of the arrays and use the index to get the corresponding values from other array
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
let m = idArray.map(function(item, index) {
// here the map method will push the object to an
// array and will return that array
return {
id: item,
date: dateArray[index],
content: contentArray[index]
}
})
console.log(m)

Your finalObj is an array of objects, so you must initialise it as an array, like this :
var finalObj = [];
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
for (var y = 0; y < dateArray.length; y++) {
finalObj.push(
{ id: idArray[y], date: dateArray[y], content : contentArray[y] }
)
}
for the "pushing to final array" part, your code inside the loop may work if you add an extra finalObj[y] = {} to initialise it and so you have :
for (var y = 0; y < dateArray.length; y++) {
finalObj[y] = {}
finalObj[y].id = idArray[y];
finalObj[y].date = dateArray[y];
finalObj[y].content = contentArray[y];
}
an it works but
finalObj.push(
{ id: idArray[y], date: dateArray[y], content : contentArray[y] }
)
is shorter and still readable i think :)

let newObjArray = idArray.map((value, index) => {
return {
id: value,
date: dateArray[index],
content:contentArray[index]
}
});
console.log(newObjArray);

Well, I'm assuming you want an Array Of Objects which has the same length with the idArrays and others.
Here's some code for that:
var finalObjArray = [];
for (var y = 0; y < dateArray.length; y++) {
finalObjArray.push({
id: idArray[y],
date: dateArrayArrange[y],
content: contentArray[y]
});
}
Basically you are adding objects to that array. Hope it helps :)

There isn’t a record of finalObj[y] when you set properties, so it return undefined instead.
To fix your problem, create a object with properties then push it to your array.

You can do it like this:
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
var final = [];
for (let y = 0; y < idArray.length; y++) {
let tmp = {};
tmp.id = idArray[y];
tmp.date = dateArray[y];
tmp.content = contentArray[y];
final.push(tmp);
}
console.log(final)
Note: dateArrayArrange does not even exist, I think you mean just dateArray

You need to create objects and add them to the array. This code should work.
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
var finalObj = [];
for (var y = 0; y < dateArray.length; y++) {
object = {};
object.id = idArray[y];
object.date = dateArray[y];
object.content = contentArray[y];
finalObj[y] = object;
}

You could collect all key value pairs (for an arbitrary count) in an object and reduce the object while mapping the values.
var id = [13, 24, 35],
date = [20181920, 20181120, 20172505],
content = ["content1", "content2", "content3"],
result = Object
.entries({ id, date, content })
.reduce((r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

by using maps we can write a function which we can extend to any number of arrays and so on. the below function takes a minimum of three distinct fields.
function joinArrays(id, date, content,...array){
const Arr = [...array];
const newArr = new Array(Arr.length)
for(let i=0; i<newArr.length;i++){
newArr[i] ={}
}
Arr.map((rowArr,index)=>{
rowArr.map((i,k)=>
{
key = arguments[index];
let obj = {};
obj[key] = i;
newArr[k]=Object.assign(newArr[k],obj)}
)
}
)
console.log(newArr);
return newArr;
}
target = joinArrays('id', 'date', 'content',idArray,dateArray,contentArray);

Related

Update value of object with values in different array

I have two array with below structure:
Array1:
[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
Array2:
[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
result
Array1 =[{id:1234,name:"macaron",quantity:"330gm",rate:"300"},{id:5678,name:"Gelato",quantity:"450gm",rate:"500"}]
I want to be able to update the only rates of objects in Array1 with rate of objects in Array2.
If order or lengths of the arrays are different one efficient way is
create a Map of the new rates from Array2 then loop over Array1 ant get() from the Map.
This way you only iterate Array2 once instead of using multiple iterations of methods like find()
let Array1=[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}],
Array2=[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}];
const rateMap = new Map(Array2.map(({id, rate})=> [id, rate]));
Array1.forEach(e=> rateMap.has(e.id) && (e.rate = rateMap.get(e.id )))
console.log(Array1)
let Array1 = [
{id:1234,name:"macaron",quantity:"330gm",rate:"100"},
{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}
];
let Array2 = [
{id:1234,name:"macaron",quantity:"600gm",rate:"300"},
{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}
];
for (i = 0; i < Array1.length ; i++) {
Array1[i].rate = Array2[i].rate
}
console.log(Array1)
Array1 = Array1.map(item => {
return { ...item, rate: Array2.filter(rec => rec.id === item.id)[0].rate };
});
});
The cleanest solution I came up with.
But as charlietfl said: I make assumtion that both lengths are the same and in same order
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
console.log(this[i].rate)
this[i].rate = array2[i].rate;
console.log(this[i].rate)
}
}
array1.updateRate(array2);
console.log(array1)
Here is second (full) solution, where that asumption isn't made:
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
for(let j = 0; j < array2.lenght;j++) {
if(this[i].id === array2[j].id) {
this[i].rate = array2[j].rate;
break;
}
}
}
}
array1.updateRate(array2);
console.log(array2)

Create an a multi diemensional array from different variables in Javascript

How do i create a multi-dimensional array from different javascript variables ?
For example, i have these three variables
var pdate = "|2019-12-26|2019-12-26|2019-12-26"
var products_id = "3354|5009|61927"
var products_category = "ENERGETICS|CASIO|SEIKO"
And i would like to transform them into this
var products_list = []
[0] = {pdate:"2019-12-26",products_id:"3354",products_category:"ENERGETICS"}
[1] = {pdate":"2019-12-26",products_id:"5009",products_category:"CASIO"}
[2] = {pdate:"2019-12-26",products_id:"61927",products_category:"SEIKO"}
Any ideas ?
Thanks
You can use the function split to separate the datas:
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
var arrayPdate = getData(pdate);
var arrayProducts_id = getData(products_id);
var arrayProducts_category = getData(products_category);
var result = []
for (let i = 0; i < arrayPdate.length; i++) {
let jsonObject = {
pdate: arrayPdate[i],
products_id: arrayProducts_id[i],
products_category: arrayProducts_category[i]
}
result.push(jsonObject)
}
console.log(result);
function getData(c) {
return c.split("|")
}
You need use .split function on your string and then use loop with array index for others.
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
pdate = pdate.split('|');
products_id = products_id.split('|');
products_category = products_category.split('|');
let arr = [];
for(let i=0; i<pdate.length; i++) {
arr.push({
pdate: pdate[i],
products_id: products_id[i],
products_category: products_category[i]
});
}
console.log(arr);

Sorting key value pair on basis of another array

I have key value pairs like :
var x={1:Car,
2: Cycle,
3:John
}
This is response coming from JSON.[Object object]
I have array like :var arr=[1,3,2]
I want to sort x as per arr .
order should be : {1:Car,3:John,2:Cycle}
In javascript how to achieve this.
You don't need to sort them, just make a new empty array and populate it by getting the values of arr and using them as the index of x.
var x = {
1: 'Car',
2: 'Cycle',
3: 'John'
};
var arr = [1, 3, 2];
var output = [];
arr.forEach(function(item){
output.push(x[item]);
});
console.log(output);
Fiddle.
var order = function(obj, arr) {
var temp = {};
for (var i = 0; i < arr.length; i++) {
temp[i] = obj[arr[i]];
}
return temp;
}
var x = {
1: "Car",
2: "Cycle",
3: "John"
}
var arr = [1, 3, 2]
x = order(x, arr);
console.log(x);

Javascript transform array into grouped object by value

I have an array:
["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"]
The array can have different sets of cars, and I want to turn it into something like this:
[{
car1: ["car1-coupe"]
},{
car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
car3: ["car3-hatchback", "car3-estate"]
}]
How can I do this in JavaScript or Underscore?
So, assuming an array like this:
var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
You can do this:
var b = a.reduce(function(prev, curr){
var car = curr.split('-')[0]; // "get" the current car
prev[car] = prev[car] || []; // Initialize the array for the current car, if necessary.
prev[car].push(curr); // Add the current item to the array.
return prev;
}, {});
This will return the following object:
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
var result = {};
for (var i = 0; i < array.length; i++) {
var key = array[i].split('-')[0]; // The car we're interested in
if (result[key]) { // Check if this car has already been initialized
result[key].push(array[i]); //add this model to the list
} else {
result[key] = [array[i]]; // initialize the array with the first value
}
}
console.log(result);
/*will return :
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
*/
var myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
var key = arr[i].split("-")[0];
myObj = {};
myObj[key] = [];
for( var j = i; j < arr.length; j+=1 ) {
if( key === arr[j].split("-")[0])
myObj[key].push(arr[j]);
}
myArr.push(myObj);
}
I think this can be done simply with this way. One loop to get the key and another inner loop to get all values of this key.

Create an array [n,[v,..,z]] from a list of key-value pairs

I have this input sample:
var c1 = "s_A_3";
var c2 = "s_B_10";
var c3 = "s_B_9";
var c4 = "s_C_18";
var c5 = "s_C_19";
var c6 = "s_C_20";
Which can easily be concatenated to:
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
And I want to convert this to a multidimensional array like this:
var groupArray = [["A",[3]],["B",[10,9]],["C",[18,19,20]]];
It's like a kind of card-sorting. How can I achieve this?
Maybe something like this:
function makeGroups(arr) {
var result = [], prev;
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (prev !== x[0]) {
prev = x[0];
result.push([prev, []]);
}
result[result.length - 1][1].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
The above method assumes the groups will be contiguous (e.g. all B_ elements appear together). In case your input may be out of order, you can tweak this algorithm to still group all elements together regardless of where they appear in the input:
function makeGroups(arr) {
var result = [], keys = {};
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (!(x[0] in keys)) {
keys[x[0]] = [];
result.push([x[0], keys[x[0]]]);
}
keys[x[0]].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","C_18","C_19","C_20","B_9"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
When you need to mention "key value pairs" in a JS program, it's usually most appropriate to use... key value pairs =D.
function solution(input) {
var kvp = {},
result = [];
input.forEach(function (el) {
var cut = el.split("_"),
alpha = cut[0],
numeric = cut[1],
elsWithSameAlpha = kvp[alpha] = kvp[alpha] || [];
elsWithSameAlpha.push(numeric);
});
Object.keys(kvp).forEach(function (key) {
result.push([key, kvp[key]]);
});
return result;
}

Categories