Array of dictionaries to a single array of dictionary in javascript - javascript

I have a javascript array as
arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}]
I want a new array as:
new_arr = [{"class":"a", "sub_class":"b", "category":"c", "sub_category":"d"}]
Is it possible to do this in Javascript without using a for loop to iterate through arr?

You can use Object.assign:
const array = [{
"class": "a"
}, {
"sub_class": "b"
}, {
"category": "c"
}, {
"sub_category": "d"
}]
const mergedObject = Object.assign({}, ...array);
// And put in an Array if that was intentional
const newArray = [mergedObject];
console.log(newArray);

I think that you want to merge objects. You could either use a spread operator or Object.assign. I don't see the point of having a single object inside an array. Considering your requirements you could do:
const merged = arr.reduce((list, curr) => {
return Object.assign({}, list, curr);
}, {});
const newArr = [merged];

You can try this.
var arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}];
var res=[];
var res1=[];
res=Object.assign(...arr);
res1.push(res);
console.log("Result: ",res1);

Related

Creating a new Array from Normal Array and Array of objects

I have two arrays, arr1 is an array of objects and arr2 is just a regular array. I am trying to match arr2 values with the "original" value from the objects of arr1 and return the "new" value into a new resulting array. There's usually more than 2 items in arr2 and the order isn't the always same that's why I couldn't just match by the index each time.
let arr1 = [
{ original: "1x Adjustments", new: "ONETIME_AMT" },
{ original: "Churn", new: "CHURN_AMT" },
{ original: "Funnel", new: "FUNNEL_AMT" },
];
let arr2 = [ '1x Adjustments', 'Churn' ]
desiredResult = ["ONETIME_AMT", "CHURN_AMT"]
I tried to use the map function multiple times, but the closest I got was only returning the first element that just happened to match, maybe I need to use a for loop in it too?
var desiredResult = arr2.map(item => item === arr1[0].original ? arr1[0].new : '')
Ideally I thought the [0] could be replaced with i (index), in a for loop but not sure how to implement a for loop in a map function (or if that's even the right solution)
Convert arr1 to a Map (arr1Map), and then map arr2, and get the new value from arr1Map:
const arr1 = [{"original":"1x Adjustments","new":"ONETIME_AMT"},{"original":"Churn","new":"CHURN_AMT"},{"original":"Funnel","new":"FUNNEL_AMT"}]
const arr2 = [ '1x Adjustments', 'Churn' ]
const arr1Map = new Map(arr1.map(o => [o.original, o.new]))
const result = arr2.map(key => arr1Map.get(key))
console.log(result)
You could also use reduce for this purpose!
let arr1 = [
{ original: "1x Adjustments", new: "ONETIME_AMT" },
{ original: "Churn", new: "CHURN_AMT" },
{ original: "Funnel", new: "FUNNEL_AMT" },
];
let arr2 = [ '1x Adjustments', 'Churn' ]
const findNew = (arr1, arr2) =>
arr1.reduce((acc, curr) => {
if(arr2.includes(curr.original)) {
acc.push(curr.new)
}
return acc
}, [])
console.log(findNew(arr1, arr2))

Print the array objects inside another array into a specific format in javascript

Generate an array of objects in a format from an array of objects inside another array .
The Given array is :
let target =
[[{key: "subscriber_id", value: "1"},
{key: "msisdn_value", value: "2"}],
[{key: "subscriber_id", value: "3"},
{key: "msisdn_value", value: "4"}
]]
The expected array of objects should be :
result = [
{"subscriber_id":"1","msisdn_value":"2"},
{"subscriber_id":"3","msisdn_value":"4"},
]
Use nested map calls with Object.fromEntries and Object.values for a clean and concise solution like so:
const result = target.map(e => Object.fromEntries(e.map(Object.values)));
Or, for a more efficient solution, use reduce:
const result = target.map(e => e.reduce((a, { key, value }) => (a[key] = value, a), {}));
You can use map and destructuring
let target = [[{key: "subscriber_id",value: "1"},{key: "msisdn_value",value: "2"}],[{key: "subscriber_id",value: "3"},{key: "msisdn_value",value: "4"}]]
let final = target.map(data => {
let [{key:a,value:b},{key:c,value:d}] = data
return { [a]:b, [c]:d }
})
console.log(final)
Loop through each element if there are more than two elements in inner arrays
let target = [[{key: "subscriber_id",value: "1"},{key: "msisdn_value",value: "2"}],[{key: "subscriber_id",value: "3"},{key: "msisdn_value",value: "4"},{key: "key",value: "value"}]]
let final = target.map((data) => {
return data.reduce((obj,{key,value})=>{
obj[key] = value
return obj
},{})
})
console.log(final)

Two object arrays: merge with same key

I have two object arrays. I want to merge with key with value
var a = [{"fit":["34","32","30","28"],"size":["x"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}]
Expected Output should be
Obj=[{"fit":["34","32","30","28","36"],"size":["x,"s","m","xl"]}]
My Code is
let arr3 = [];
b.forEach((itm, i) => {
arr3.push(Object.assign({}, itm, a[i]));
});
alert(JSON.stringify(arr3))
it gives [{"size":["x"],"fit":["34","32","30","28"]}] which wrong.
Use Array.reduce().
// Combine into single array (spread operator makes this nice)
const myArray = [...a, ...b];
// "reduce" values in array down to a single object
const reducedArray = myArray.reduce((acc, val) => {
return [{fit: [...acc.fit, ...val.fit], size: [...acc.size, ...val.size]}];
});
Edit: if you want the reducer to merge objects regardless of what keys and fields it has then you can do by iterating over the keys of the objects and merging them dynamically:
const reducedArray = myArray.reduce((acc, val) => {
const returnObject = {};
for (const eaKey in acc) {
returnObject[eaKey] = [...acc[eaKey], ...val[eaKey]];
}
return [returnObject];
});
If the fields of the objects aren't guaranteed keys then you will need to get even more dynamic in detecting the type of merge and how to do it, but it's possible and I will leave that as an exercise for you to figure out. :)
Note that if there are duplicate values in each of the "fit" and "size" arrays, they will not be deduplicated. You'd have to do that manually as a separate step either with extra logic in the reduce function or afterwards.
combine a and b in a single array then reduce it starting with an array having an object with empty fit and size arrays:
var a = [{ fit: ["34", "32", "30", "28"], size: ["x"] }];
var b = [{ size: ["s", "m", "xl"], fit: ["36"] }];
var obj = [...a, ...b].reduce(
(acc, curr) => {
Object.keys(curr).forEach(k => {
acc[0][k] = [...new Set([...(acc[0][k] || []), ...curr[k]])];
});
return acc;
},
[{}]
);
console.log(obj);
You can create a combine function that takes fit and size from any two objects and merges them.
Use it as a reducer to combine everything.
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
Example:
var a = [{"fit":["34","32","30","28"],"size":["x"]}, {"fit": ["10", "11"], "size":["xxxxxxxxl"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}];
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
console.log(result);
If you don't want to use the keys directly you could try
const arr3 = b.reduce((carry, current, index) => {
Object.keys(current)
.forEach(key => {
Object.assign(carry, { [key]: Array.prototype.concat.call(current[key], a[index][key])});
});
return carry;
}, {});

How to convert an array to an object?

I have some data that comes like an array, i will show you it looks
Vm.table=[{
Name:"amina";
},
{
Prenom:"adfe";
},
{
Region:"rabat";
}];
To an object like
Vm.obj={
Name:"amina",
Prenom:"adfe",
Region:"rabat"
};
I need to set a code that may convert the table to this object, i put a lot of functions but is not working to me if someone can help.
You can use Object.assign() and spread operator
const table=[{Name:"amina"},{Prenom:"adfe"},{Region:"rabat"}];
const result = Object.assign({}, ...table);
console.log(result);
You can use reduce
Vm.obj = Vm.table.reduce((obj, col) => {
Object.keys(col).forEach(k => obj[k] = col[k])
return obj;
}, {});
Of course, if you have repeating keys, this will take the last key/val pair available.
Use Array.prototype.reduce and I am assuning objects have only single key, value pair.
let array =[{
Name:"amina"
},
{
Prenom:"adfe"
},
{
Region:"rabat"
}];
let obj = array.reduce((prev, curr) => {
const key = Object.keys(curr)[0];
prev[key] = curr[key];
return prev;
}, {});
console.log(obj);

Set First Value as Key in Javascript Array

Creating an array based off selected DataTables Rows
$('#savenlp').click(recordjourney);
function recordjourney() {
var data = table.rows(['.selected']).data().toArray();
console.log( (data) );
console.log( JSON.stringify(data) );
}
data returns
0 : (8) ["Which", "TitleCase", "QuestionWord", "", "", "", "", ""]
JSON.stringify(data) returns
[["baseball","Noun","Singular","","","","",""]]
This information is dynamically generated, so I am just looking to take the first value (in this case baseball) and turn it into something like
"baseball": [
"Noun",
"Singular"
]
I can return the first value (the key I want using)
alert(data[0][0]);
I am much more adept in PHP but I am learning javascript/jquery more and more.
It is my understanding javascript does not have associative arrays, so I am a bit confused as to how to generate this.
const data = [
["baseball","Noun","Singular","","","","",""],
["baseballs","Noun","","Plural","","","","",]
];
const mappedData = data.reduce((acc, row) => { acc[row.shift()] = row.filter(d => d !== ''); return acc; }, {});
console.log(mappedData);
We can use object destructuring and spread operators for ease of use.
In the example below, the key will be the first item and all the rest items will be placed in the newData variable
const data = [["baseball","Noun","Singular","","","","",""]];
const [key, ...newData] = data[0]
// if you want the new data to not have empty entries, simple apply the filter
const newDataFiltered = newData.filter(item => !!item)
const objWithEmpty = {[key]: newData}
const objWithoutEmpty = {[key]: newDataFiltered}
console.log(objWithEmpty, objWithoutEmpty)
For multiple arrays inside the outer array, just enclose the whole logic inside a for loop
const data = [
["baseball","Noun","Singular","","","","",""],
["baseball1","Noun1","Singular1","","","","",""],
["baseball2","Noun2","Singular2","","","","",""]
];
const objWithEmpty = {}
const objWithoutEmpty = {}
data.forEach((array) => {
const [key, ...newData] = array
// if you want the new data to not have empty entries, simple apply the filter
const newDataFiltered = newData.filter(item => !!item)
objWithEmpty[key] = newData
objWithoutEmpty[key] = newDataFiltered
})
console.log(objWithEmpty, objWithoutEmpty)
Simply extract the desired values from data and put them into an object formatted as you like:
const data = [["baseball","Noun","Singular","","","","",""]];
const firstArr = data[0];
const transformedFirstObject = {
[firstArr[0]]: [firstArr[1], firstArr[2]],
};
console.log(transformedFirstObject);
But it's pretty weird to have an object with only one property like that. If your data might have more than one sub-array in it and you want to turn the array of arrays into an array of objects, use map:
const data = [
["baseball","Noun","Singular","","","","",""],
["foo","bar","baz","","","","",""]
];
const transformed = Object.assign(...data.map(([prop, value1, value2]) => ({ [prop]: [value1, value2] })));
console.log(transformed);
A bit simpler compared to other answers here but works as well.
const data = [
["baseball","Noun","Singular","","","","",""],
["baseball1","Noun1","Singular1","","","","",""],
["baseball2","Noun2","Singular2","","","","",""]
];
const obj = [];
data.forEach(function(i) {
let jsonObj = {};
jsonObj [i[0]] = i.slice(1).filter(x=>x !='');
obj.push(jsonObj)
});
console.log(JSON.stringify(obj))
Just using forEach, considering multiple array elements.
var obj = {};
var arr = [
["baseball", "Noun", "Singular", "", "", "", "", ""],
["Test", "Test1", "Test2", "", "", "", "", ""]
];
arr.forEach(function(val, idx) {
val.forEach(function(val1, idx1) {
if (idx1 === 0) {
obj[val1] = val.slice(1, val.length)
}
})
})
console.log(JSON.stringify(obj))

Categories

Resources