This question already has answers here:
Convert array of strings into an array of objects
(6 answers)
Closed 1 year ago.
I have this code
const jsonArray = [1,2,3,4,5];
I want to convert it so I can get
{
"id" : 1
},
{
"id" : 2
},
{
"id" : 3
},
{
"id" : 4
},
{
"id" : 5
}
So I need to add "id" key for all the objects outputs
Try the map function
jsonObjectArray = jsonArray.map((ele) => {return {"id": ele}})
You can use map.
jsonArray.map(id=>({id}))
You could use Array.prototype.map() for that:
const jsonArray = [1,2,3,4,5];
const arrayofObjects = jsonArray.map(e => ({id: e}))
console.log(arrayofObjects);
Related
This question already has answers here:
How to find an appropriate object in array by one of its properties
(3 answers)
Closed 29 days ago.
I have a array as follows :
data = [
{
"data": {
"id":1,
"vol":"0.0"
"requiredId":100
"details":{
"ABC":"8.30",
"OFG":"13.85",
"SPG":"70.80"
}
}
},
{
"data": {
"id":2,
"vol":"1.0",
"requiredId":2
"details":{
"ABC":"3.30",
"OFG":"15.85",
"SPG":"70.80"
}
}
}
]
I just want to get the object from this array where id is equal to requiredId. How can I do that?
data.find(item => item.data.id === item.data.requiredId)
This question already has answers here:
Group array items using object
(19 answers)
Closed 3 months ago.
I have an array which has keys eventId and selectedNumber. In the array same eventid can be present in multiple objects but selectedNumber value will be always different. My aim is to make a nested array in which each object will have unique eventId But selectedNumber will become an array having numbers from each of those objects having the same eventId. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as eventId. I don't want that. Anyway to do it?
Input:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
Result:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : ["20", "30"]
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
let newarr = []
oldArr.map((x,i)=>{
if(i==0){
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr newarr.push(x)
}else{
if(oldArr[i].eventId == oldArr[i-1].eventId){
const temp = x.selectedNumber
delete x.selectedNumber
newarr[i-1].numArr.push(temp)
}else{
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr
newarr.push(x)
}
}
})
Just reduce your input to an object, and map the object entries to the desired array format:
const input = [{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}];
const result = Object.entries(input.reduce((a, {eventId, selectedNumber}) => {
a[eventId] = a[eventId] || [];
a[eventId].push(selectedNumber)
return a;
}, {})).map(([eventId, selectedNumber]) => ({ eventId, selectedNumber }));
console.log(result);
Instead of creating the intermediate lookup object, you could directly reduce to an array, but it will have a negative impact on the solution's time complexity.
This question already has answers here:
Group by array and add field and sub array in main array
(8 answers)
Closed 1 year ago.
As a newbie, I'm looking for the best approach to achieve the below:
Here is the Array I get from my DB query that contains a left join on the "class" table
[
{"legnumber":1,
"classcode" : "J"},
{"legnumber":1,
"classcode" : "Y"},
{"legnumber":2,
"classcode" : "J"}
]
And I would like to get something like this:
{
"legs": [
{
"legnumber" : 1,
"classes" : [
{"classcode" : "J"},
{"classcode" : "Y"}
]
},
{
"legnumber" : 2,
"classes" : [
{"classcode" : "J"}
]
}
]
}
Thanks a lot for your suggestions.
I'm using Sequelize in this project but I'm writing raw queries as I find it more convenient for my DB model.
Regards,
Nico
Hassan's answer is the more concise way to handle this, but here is a more verbose option to help understand what's happening:
const queryResults = [
{ legnumber: 1, classcode: 'J' },
{ legnumber: 1, classcode: 'Y' },
{ legnumber: 2, classcode: 'J' },
]
// create an object to store the transformed results
const transformedResults = {
legs: [],
}
// loop through each item in the queryResult array
for (const result of queryResults) {
// try to find an existing leg tha matches the current leg number
let leg = transformedResults.legs.find((leg) => leg.legnumber === result.legnumber)
// if it doesn't exist then create it and add it to the transformed results
if (!leg) {
leg = {
legnumber: result.legnumber,
classes: [],
}
transformedResults.legs.push(leg)
}
// push the classcode
leg.classes.push({ classcode: result.classcode })
}
console.log(transformedResults)
You can group your array items based on legnumber using array#reduce and then get all the values to create your result using Object.values().
const arr = [ {"legnumber":1, "classcode" : "J"}, {"legnumber":1, "classcode" : "Y"}, {"legnumber":2, "classcode" : "J"} ],
output = arr.reduce((r, {legnumber, classcode}) => {
r[legnumber] ??= {legnumber, classes: []};
r[legnumber].classes.push({classcode});
return r;
},{}),
result = {legs: Object.values(output)};
console.log(result);
This question already has answers here:
Add element to multidimensional array
(4 answers)
Closed 3 years ago.
Working with Angular 5.
What I am trying to do is to assign in array a multidimensional array.
What is working with PHP?
$arM = array();
$arM["20/02/2020"][1] = ["name"=> 'my name', "id"=> 1];
the output of this is:
Array
(
[20/02/2020] => Array
(
[1] => Array
(
[name] => my name
[id] => 1
)
)
)
In angular when I am doing this is not working. Example:
let data:any = [];
data["20/02/2020"][1] = myArray;
How can I achieve the same result of PHP's?
Like this maybe?
let data = {}; // Object (with keys), not array
data["20/02/2020"] = { name : "my name", id : 1 };
console.log(data);
let data:Object = {
"20/02/2020":[
{"name":"my name", "id": 1},
{"name":"my name2", "id": 2},
{"name":"my name3", "id": 3}
]
};
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 3 years ago.
I have a couple of objects inside of an array :
array1 =[{name : "Cena", age : 44},{job : "actor", location : "USA"}]
is there a way for me to merge these two objects to get something like :
array2 =[{name : "Cena", age : 44, job : "actor", location : "USA"}]
I tried looping through the elements but it is not a good option if the object is a big one, I guess. Any good solution using typescript?
You can use Array.prototype.reduce:
const array1 = [{ name: "Cena", age: 44 }, { job: "actor", location: "USA" }];
const array2 = [array1.reduce((acc, cur) => ({ ...acc, ...cur }))];
console.log(array2);