This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 5 years ago.
I have JSON array like this:
var items = [
[{id:1,name:'test'},{id:2,name:'test'},...] ,
[{id:1,name:'test'},{id:2,name:'test'},...] ,
]
From that I need an array like this:
var newArray = [
{ id: 1, name: 'test' }, { id: 2, name: 'test'}, { id: 3, name: 'test'}, ...
]
Now I am using a for loop on items array and storing into newArray but is there any other method without using loops?
I love functional and new prototpes of array so here is my demo
var items = [
[{id:1,name:'test'},{id:2,name:'test'}] ,
[{id:1,name:'test'},{id:2,name:'test'}]
]
var ll = items.reduce(function(prev, current){return prev.concat(current)})
console.log(ll)
Demo 1: concat() and .apply()
Demo 2: reduce() and concat()
Demo 3: ... Spread Operator and concat()
Demo 1
var items = [
[{id:1,name:'test'},{id:2,name:'test'}] ,
[{id:1,name:'test'},{id:2,name:'test'}] ,
]
var flattened = [].concat.apply([], items);
console.log(flattened);
Demo 2
var items = [
[{id:1,name:'test'},{id:2,name:'test'}],
[{id:1,name:'test'},{id:2,name:'test'}]
];
var flattened = items.reduce(function(prev, curr) {
return prev.concat(curr);
});
console.log(flattened);
Demo 3
var items = [
[{id:1,name:'test'},{id:2,name:'test'}],
[{id:1,name:'test'},{id:2,name:'test'}]
];
var flattened = [].concat(...items);
console.log(flattened);
Related
This question already has answers here:
How to merge two array of objects with reactjs?
(4 answers)
Closed 11 months ago.
how to merge array of this in react or javascript..can anyone help me with this i want the output something like..all the test array should be in one array...coz i need to find the minimum price and plus i need to show the mapping in ascending order
array :[
{
id:0,
name:'something',
test: [
{
id: 0,
test_name:'blood',
price:'200',
},
{
id:1,
test_name:'kidney',
price:'300',
}
]
},
{
id:1,
name:'something1',
test: [
{
id: 0,
test_name:'blood2',
price:'100',
},
{
id:1,
test_name:'kidney2',
price:'100',
}
]
}
]
You can use spread operator to merge two array.
var a = [{fname : 'foo'}]
var b = [{lname : 'bar'}]
var c = [...a, ...b] // output is [{fname : 'foo'},{lname : 'bar'}]
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);
For example this is the original array
[
{name:xyz,id:123 },
{name:abc,id:232},
]
Now here is an another array
[
{value:'anything'},
{value:'anything12312'}
]
Now in new array or original array the output should be this
[
{value:'anything',name:xyz,id:123},
{value:'anything12312', name:abc,id:232}}
]
How can I achieve this
you mean like this ??
Use map,index and spread as :
let a = [
{name:"xyz",id:123 },
{name:"abc",id:232},
]
let b = [
{value:'anyrhing'},
{value:'anything12312'}
]
let res = a.map((el,idx)=> ({...el,...b[idx]}));
console.log(res)
Use object destructuring.
const arr1 = [
{name:'xyz',id:123 },
{name:'abc',id:232},
]
const arr2 = [
{value:'anyrhing'},
{value:'anything12312'}
]
const arr3 = [];
for(let i=0;i<arr1.length;i++)
arr3.push({...arr2[i],...arr1[i]});
A1=[
{name:"xyz",id:123 },
{name:"abc",id:232},
];
A2=[
{value:'anyrhing'},
{value:'anything12312'}
];
obj1={
...A2[0],
...A1[0]}
//another method to merge objects
obj2=Object.assign(A2[1],A1[1]);
//The result you needed
A3=[obj1,obj2];
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:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
I have an array of json objects:
[ {id:0, name:'A'}, {id:1, name:'B'}...{id:n, name:'N'} ]
How do i get the value (name) base on a given id, without iterating the array? Perhaps using map or some filter method...
const arr = [ {id:0, name:'A'}, {id:1, name:'B'},{id:3, name:'N'} ];
const inputId = 1;
const foundObj = arr.find(({ id }) => id === inputId);
if (foundObj) console.log(foundObj.name);
This still does iterate the array internally, though (as any method will).
This find method will find object based on your object property and value.
ArrayName.find(x => x.id === 0);
let array = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:'n', name:'N'} ]
//To search in array we must iterate. But if you want to optimise performance for multiple searches you can map it to object by id.
let map = array.reduce((acc,element)=>{acc[element.id]=element;return acc;},{})
console.log(map[0])
console.log(map[1])
console.log(map.n) //As n was used as id.
Maps take one iteration to construct. Value retrieval thereon is sublinear.
// Input.
const input = [{id: 0, name:'A'}, {id: 1, name:'B'}, {id: 13, name:'N'}]
// To Map.
const toMap = (A) => new Map(A.map(x => [x.id, x]))
// Output.
const output = toMap(input)
// Proof.
console.log(output.get(0))
console.log(output.get(1))
console.log(output.get(13))
When you want to find an element in a collection, array might not be the best choice, objects or maps are much better in that case.
Each time you have to find an element, you would have to iterate over the array which would take O(n) time.
To avoid this, you could have an API layer in the middle, to convert your array into an a data structure which maps values by unique keys. You could achieve this by a plain Javascript Object.
That way you could find your element by id in O(1) without any iteration.
//original data
let arr = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:2, name:'N'} ];
//convert it into object
let obj = arr.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
//modified data
{ 0: { id: 0, name: 'A' },
1: { id: 1, name: 'B' },
2: { id: 2, name: 'N' } }
//Now, you can look up value on any id as
obj[id].name;