How to merge object inside object [duplicate] - javascript

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 4 years ago.
I have an array
var input = [["group1","group2","group3" ], ["group1", "group5" ]]
I would like to merge two objects like this :
["group1","group2","group3", "group1", "group5" ]
I tried to merge two objects in one array, however, I couldn't get the answer.
Any help would be appreciated.

I'm not too familiar with js, but can't you concat two arrays with something like
var merged = input[0].concat(input[1]);

You can use concat() like so:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = [].concat.apply([], input);
console.log(output);
Or alternatively, Array.prototype.flat():
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input.flat(1);
console.log(output);
Or if that is "hard" data, and will not change, you could use an even simpler concat() operation:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input[0].concat(input[1]);
console.log(output);

You can use the concat function to combine the arrays.
const resultArr = [];
input.forEach(curr => {
resultArr.concat(curr);
});

You're talking about 'flattening the array'...
const flatten = (array) => {
return array.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten([[1,2,[3]],4]));

ES5
array.reduce(function(a, x) { return a.concat(x); }, []);
ES6
array.reduce((a, x) => a.concat(x), []);

There is multiple approaches that you could take, my favorite would be to use the reduce method to transform your bi-dimensional array into one flat array and it would look like this :
function reducer(final_flat_array, inputItem) {
return [...final_flat_array, ...inputItem]
};
let flat_array = input.reduce(reducer, []);
or a more 'imperative' way I guess :
let flat_array = [];
input.forEach(item => flat_array.push(item);

Related

JAVASCRIPT Search in 3D array of objects [duplicate]

This question already has an answer here:
Search in multi dimension Array in JAVASCRIPT [closed]
(1 answer)
Closed last year.
I have an array with some data like this :
const
data = [
{"key":9054,"title":"1","children":[
{"key":8959,"title":"1-0","idFather":8959,"tableIsFamily":false,"children":[]},
{"key":8943,"title":"1-1","idFather":8943,"tableIsFamily":false,"children":[]},
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":8969,"title":"1-3","idFather":8969,"tableIsFamily":false,"children":[]}]},
{"key":9040,"title":"2","children":[
{"key":8957,"title":"2-0","idFather":8957,"tableIsFamily":false,"children":[]},
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
{"key":9855,"title":"2-1-1","idFather":8941}
]},
{"key":8949,"title":"3-0","idFather":8949,"tableIsFamily":false,"children":[]},
{"key":8983,"title":"3-1","idFather":8983,"tableIsFamily":false,"children":[]},
{"key":10070,"title":"3-2","idFather":10070,"tableIsFamily":false,"children":[]}
]}
];
And I have another array with some Id's like this :
[9054, 9021, 9040, 8941, 8947]
I want to filter the data array and get only matched array with the second array, I have tried some map/filter but it seem to be more difficult thann i think, Have you any ideas how to deal with this array please ?
The expected output should be :
const
data = [
{"key":9054,"title":"1","children":[
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":9040,"title":"2","children":[
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
]},
]}
];
Thank you!
You can use rectursive function for deep datas. Like this.
This function can also be used for deeper structures.
Further information about the recursive function here: https://www.geeksforgeeks.org/recursive-functions/#:~:text=In%20programming%20terms%2C%20a%20recursive,can%20be%20solved%20quite%20easily.
const
data = [
{"key":9054,"title":"1","children":[
{"key":8959,"title":"1-0","idFather":8959,"tableIsFamily":false,"children":[]},
{"key":8943,"title":"1-1","idFather":8943,"tableIsFamily":false,"children":[]},
{"key":9021,"title":"1-2","idFather":9021,"tableIsFamily":false,"children":[]},
{"key":8969,"title":"1-3","idFather":8969,"tableIsFamily":false,"children":[]}]},
{"key":9040,"title":"2","children":[
{"key":8957,"title":"2-0","idFather":8957,"tableIsFamily":false,"children":[]},
{"key":8941,"title":"2-1","idFather":8941,"tableIsFamily":false,"children":[
{"key":8947,"title":"2-1-0","idFather":8941},
{"key":9855,"title":"2-1-1","idFather":8941}
]},
{"key":8949,"title":"3-0","idFather":8949,"tableIsFamily":false,"children":[]},
{"key":8983,"title":"3-1","idFather":8983,"tableIsFamily":false,"children":[]},
{"key":10070,"title":"3-2","idFather":10070,"tableIsFamily":false,"children":[]}
]}
];
const ids = [9054, 9021, 9040, 8941, 8947]
filterData = (data)=> {
const newData = data.filter((obj)=>ids.includes(obj.key));
newData.forEach((obj)=>{obj.children ? obj.children = filterData(obj.children) : []});
return newData;
}
console.log(filterData(data));

Convert Json Array to single Object in Node JS [duplicate]

This question already has answers here:
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I want to convert JSON array to a single object. PFB the details
Array:
[{ "item-A": "value-1" }, { "item-B": "value-2" }]
Expected Result:
{ "item-A": "value-1", "item-B": "value-2" }
I have tried following options but result is not what I was expecting
let json = { ...array };
json = Object.assign({}, array);
json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
Result:
{"0":{"item-A":"value-1"},"1":{"item-B":"value-2"}}
You can use Object.assign and spread the array
const arr=[{ "item-A": "value-1" }, { "item-B": "value-2" }];
console.log(Object.assign({},...arr));
You can use reduce like how you did it with more attention like this:
let array = [{ "item-A": "value-1" }, { "item-B": "value-2" }];
let object = array.reduce((prev, curr) => ({ ...prev, ...curr }), {});
console.log(object);

Find the element in json - Using underscore library or other way

I want to find the g:id object in the below given array of objects
If my g:id is like "g:id": "121"
I can find the element like
var item = _.findWhere(obj, {'g:id': '121'});
But what i have is "g:id": ["121"] like an array. How can i find it.
Here's my array of objects.
[
{
"g:id": [
"121"
],
"g:item_group_id": [
"90461"
]
},
{
"g:id": [
"129"
],
"g:item_group_id": [
"90462"
]
}
]
I tried like this var item = _.findWhere(jsonXML, {'g:id'.[0]: '121'}); but it is not valid.
How can i do this by underscore.js or any other way ?
You can use Array.find() with destructuring to get the g:id value from the array:
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': [gid] }) => gid === '121')
console.log(result)
Another option is to use Array.includes() to see if the array contains the value (a must if the array may contain more the one value):
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': gid }) => gid.includes('121'))
console.log(result)

Grouping with Lodash

I'm trying to group by "date" an object like this:
let myObj = [
{"date":"01/12","Deposits":50000},
{"date":"01/12","Withdrawals":10000}
]
So if I did groupBy "date", I'd want to receive:
[
{"date":"01/12", "Deposits":50000, "Withdrawals":10000}
]
I tried many different ways without success =(
Here is an approach without lodash, by using .reduce() and the spread syntax ... to extract your wanted properties. By using .reduce() you can group your array's objects into a larger aggregation object (ie: the acc), which you can then get the values() of to get your array of results:
const myObj = [{"date":"01/12","Deposits":50000},{"date":"01/12","Withdrawals":10000}];
const res = Object.values(myObj.reduce((acc, {date, ...rest}) => {
acc[date] = {...(acc[date] || {date}), ...rest};
return acc;
}, {}));
console.log(res);
If you wish to use lodash, here is an approach using _.groupBy(), _.map(), _.assign() and _.flow() which will allow you to make your own function to merge arrays by a key:
const myObj = [{"date":"01/12","Deposits":50000}, {"date":"01/12","Withdrawals":10000}];
const mergeArr = _.flow(
arr => _.groupBy(arr, 'date'),
group => _.map(group, arr => _.assign({}, ...arr))
);
const res = mergeArr(myObj);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
let result = _.map(_.groupBy(myObj, 'date'), value => _.assign(...value));

How can I filter by all the properties in an array of objects? [duplicate]

This question already has answers here:
Filter array of objects on all properties value
(3 answers)
Closed 5 years ago.
Suppose I have an array like this:
const people = [
{
"name":"pete22",
"age":56
},
{
"name":"sonya56",
"age":22
}
]
I can filter with lodash like this by name:
let result = people.filter(person =>_.includes(person.name,'56')
//{'name':'sonya56'}
What if I want to return all people with '56' in any property? So in the above example it would return both people? I am looking for a compact solution, maybe lodash?
You don't need Lodash to do this as JavaScript natively has support to do these kind of things.
What you need to do is filter the people but also filter each value inside an entry, e.g.:
const people = [{
"name": "pete22",
"age": 56
}, {
"name": "sonya56",
"age": 22
}]
// Filter your 'people' JSON
const filteredPeople = people.filter(person => {
// Filter each 'value' (property) inside each entry in 'people'
return Object.values(person).filter(value => {
// Turn a value into a string and check if it includes the value '56'
return value.toString().includes('56')
})
})
console.log(filteredPeople)
You could just use Array#filter with Object.values, Array#map with strings and check with Array#some and Array#includes.
const
people = [{ name: "pete22", age: 56 }, { name: "sonya56", age: 22 }],
filteredPeople = people.filter(person => Object
.values(person)
.map(String)
.some(v => v.includes('56'))
)
console.log(filteredPeople);
What if I want to return all people with '56' in any property?
You need an array with all such properties with which you want to filter the input array.
var prop = [ "age", "size" ];
Now simply applies the filter in a loop
var valueToMatch = "56";
result = people;
prop.forEach( function( key ){
if ( result.length ) { return true; } //if the result is already empty
result = result.filter( function( peopleObj ){
peopleObj[ key ] == valueToMatch;
});
});
result is the output array filtered with all the properties given in prop array.
Stop using lodash for everything.
JavaScript:
let filtered = people.filter((e) => e.name === ‘foo’ && e.age === 23);
Keep in mind that && forces the two conditions and || says that only one of them must be true.
Extended solution for any number of properties:
var people = [
{ "name":"pete22", "age":56 }, {"name":"sonya56", "age":22 },
{ "name":"john33", "age":33 }, {name: "mike", "login":"56mike", "code": 10 }
],
result = people.filter(function(o){
return Object.keys(o).some(function(k){ return String(o[k]).indexOf("56") !== -1; });
});
console.log(result);
We can filter again with values of Object
people.filter(
hm=>Object.values(hm).filter(
vl=>(vl+'').indexOf(56)>-1).length>0)

Categories

Resources