combining two set of data in javascript [duplicate] - javascript

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 4 years ago.
Im trying to combine two sets of data.
var a = [{ Id: 1, Name: 'foo' },
{ Id: 2, Name: 'boo' }];
var b = [{ Id: 3, Name: 'doo' },
{ Id: 4, Name: 'coo' }];
Most of question here i found is only a normal array.
I've tried Object.assign(a, b); but it only returns the b value.
The a and b data is from the server side.
Thanks for the help.

Try array concat
var a = [{ Id: 1, Name: 'foo' },
{ Id: 2, Name: 'boo' }];
var b = [{ Id: 3, Name: 'doo' },
{ Id: 4, Name: 'coo' }];
let c = a.concat(b);
console.log(c);

Using spread syntax
var a = [{ Id: 1, Name: 'foo' },
{ Id: 2, Name: 'boo' }];
var b = [{ Id: 3, Name: 'doo' },
{ Id: 4, Name: 'coo' }];
c = [...a, ...b];
Note: Spread syntax is not supported by all browsers , its ok if you use es6/5 compiler though like babel. See Spread
Another option is

Related

JavaScript get the element in array of object [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 2 years ago.
I have 2 Array:
const arr1 = [
{
id: 1,
name: "a"
},
{
id: 2,
name: "ab"
},
{
id: 3,
name: "abc"
}]
and
const arr2 = [{id:"1"}, {id:"3"}]
How can i get from two above array to get the result like that:
const result = ["a", "abc"]
I'm struggling with array built-in function. Thank you for reading.
You could do something like the following.
const arr1 = [{ id: 1, name: "a"}, {id: 2, name: "ab"}, { id: 3, name: "abc" }]
const arr2 = [{ id: 1 }, { id: 3 }];
const ids = arr2.map(item => item.id);
const includedIds = arr1.filter(item => ids.includes(item.id)).map(item => item.id)
console.log(includedIds)

How to avoid override of a list element in javascript? [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Do objects pushed into an array in javascript deep or shallow copy?
(2 answers)
Closed 2 years ago.
If you run the code snippet below you can observe the following:
at first console.log() it print 0,Jhon after I modified the first element of the first array the same change is also reversed on the object in the second list, why?
its possible to avoid this?
This is a sample of this problem:
var myArray = [{
id: 0,
name: "Jhon"
},
{
id: 1,
name: "Sara"
},
{
id: 2,
name: "Domnic"
},
{
id: 3,
name: "Bravo"
}
];
var a = [];
a.push(myArray[0]);
console.log(a);
myArray[0].name = 'TEST';
console.log(a);
If you dont want it to be by reference, you can use spread syntax
a.push({...myArray[0]});
complete code:
var myArray = [{
id: 0,
name: "Jhon"
},
{
id: 1,
name: "Sara"
},
{
id: 2,
name: "Domnic"
},
{
id: 3,
name: "Bravo"
}
];
var a = [];
a.push({...myArray[0]});
console.log(a);
myArray[0].name = 'TEST';
console.log(a);

Function question, angular typescript, match id values from 2 arrays to get the index from one of them

I have a two arrays, and I want to match their ID values and then get the index of that id in the second array. I know this sounds simple but I'm super new to the syntax, and I'm having a hard time picturing what this should look like. can anyone model that in simple terms?
example functionality:
var array1 = { id:2, name: 'preston'}
array2 = {
{
id: 1
name: 'john'
},
{
id: 2
name: 'bob'
}
Expected behavior
where both ids = 2, give index of array2.
returns 1
can anyone show me?
You can use findIndex on array2
Try this:
var array1 = {
id: 2,
name: 'preston'
}
var array2 = [{
id: 1,
name: 'john'
},
{
id: 2,
name: 'bob'
}
]
console.log(array2.findIndex(item => item.id === array1.id))
Or use indexOf with map if you want support for IE as well without polyfills.
var array1 = {
id: 2,
name: 'preston'
}
var array2 = [{
id: 1,
name: 'john'
},
{
id: 2,
name: 'bob'
}
]
console.log(array2.map(item => item.id).indexOf(array1.id))
Iterate over each item in array1 using forEach(). Find each item's index in array2 using findIndex().
var array1 = [{id:2, name: "preston"}];
var array2 = [{id: 1, name: "john" }, {id: 2, name: "bob" }];
array1.forEach(item => {
let index = array2.findIndex(obj => obj.id === item.id);
console.log(index);
});

ramda function javascript on arrays

const censusMembers = Object.freeze([
{
id: 1,
name: 'Bob'
}, {
id: 2,
name: 'Sue'
}, {
id: 3,
name: 'Mary',
household_id: 2
}, {
id: 4,
name: 'Elizabeth',
household_id: 6
}, {
id: 5,
name: 'Tom'
}, {
id: 6,
name: 'Jill'
}, {
id: 7,
name: 'John',
household_id: 6
}
]);
In this array, A dependent can be determined by the presence of a household_id. The household_id is a reference to the ID of the employee that that member is a depended of (ex in the censusMembers list 'Mary' is a dependent of 'Sue')
How to build a function that takes in an id and the array of members(census members) and returns all dependents that belong to the user that has that id.
If the id is of a dependent, or isn't in the censusMember array then the function should return null.
If there are no dependents then the function should return an empty arrray.
for example:
if I give input as id 6
then output shoul be
[
{"id":4,"name":"Elizabeth","household_id":6},
{"id":7,"name":"John","household_id":6}
]
Here is code that seems to do what you would like:
const {curry, find, propEq, has, filter} = R
const householdMembers = curry((census, id) => {
const person = find(propEq('id', id), census);
return person
? has('household_id', person)
? null
: filter(propEq('household_id', id), census)
: null
})
var censusMembers = Object.freeze([
{id: 1, name: 'Bob'},
{id: 2, name: 'Sue' },
{id: 3, name: 'Mary', household_id: 2 },
{id: 4, name: 'Elizabeth', household_id: 6},
{id: 5, name: 'Tom'},
{id: 6, name: 'Jill'},
{id: 7, name: 'John', household_id: 6}
])
const householders = householdMembers(censusMembers)
console.log(householders(6))
//=> [
// {id: 4, name: 'Elizabeth','household_id': 6},
// {id: 7, name: 'John', 'household_id': 6}
// ]
console.log(householders(7)) //=> null
console.log(householders(8)) //=> null
console.log(householders(5)) //=> []
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
But I would suggest that you might want to rethink this API. The empty array is a perfectly reasonable result when nothing is found. Making it return null for some of these cases makes the output much harder to use. For instance, if you wanted to retrieve the list of names of household members, you could simply write const householderNames = pipe(householders, prop('name')). Or you could do this if your function always returned a list.
Having a single function return multiple types like this is much harder to understand, and much, much harder to maintain. Note how much simpler the following version is, one that always returns a (possibly empty) list:
const members = curry((census, id) => filter(propEq('household_id', id), census))

How to extend array object by another array using Underscore.JS [duplicate]

This question already has answers here:
Combine two arrays of objects using underscore
(4 answers)
Closed 5 years ago.
I have below list objects:
Object 1:
[{
empId: 1,
name: AAA,
schoolId: 1
}, {
empId: 2,
name: BBB,
schoolId: 2
}]
And Object 2:
[{
schoolId: 1,
schoolName: SchoolA
}, {
schoolId: 2,
schoolName: SchoolB
}]
In both objects Object1 and Object2, SchoolId is common field. Which can be accessed as a mapping field.
Now I using _.extend method of UnderscoreJS I want to achieve below object:
Output:
[{
empId: 1,
name: AAA,
schoolId: 1,
school: SchoolA
}, {
empId: 2,
name: BBB,
schoolId: 2,
school: SchoolB
}]
Can you please suggest how can I achieve this ? Thanks
Create an index (arr1Index) by schoolId of 1st array using _.indexBy(), then _.map() the 2nd array, and create a new object that extends the current object, with an object with the same schoolId from the arr1Index:
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];
var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];
var arr1Index = _.indexBy(arr1, 'schoolId');
var result = _.map(arr2, function(o) {
return _.extend({}, o, arr1Index[o.schoolId]);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can combine each and findWhere as below.
var d1 = [{
empId: 1,
name: "AAA",
schoolId: 1
}, {
empId: 2,
name: "BBB",
schoolId: 2
}];
var d2 = [{
schoolId: 1,
schoolName: "SchoolA"
}, {
schoolId: 2,
schoolName: "SchoolB"
}];
var output = _.each(d1, function(obj) {
obj.school = _.findWhere(d2, {
schoolId: obj.schoolId
}).schoolName;
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can use _extend and _find
var arr1 = [{"empId":1,"name":"AAA","schoolId":1},{"empId":2,"name":"BBB","schoolId":2}];
var arr2 = [{"schoolId":1,"schoolName":"SchoolA"},{"schoolId":2,"schoolName":"SchoolB"}];
var output = _.each(arr1, function(a1) {
_.extend(a1, _.find(arr2, function(a2) {
return a2.schoolId == a1.schoolId;
}))
});
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can do it this way (Note: This solution expects that we have two arrays with the same length and the N-th element of the first array should be extended with the N-th element of the second array etc.):
var arrayOne = [{
empId: 1,
name: 'AAA',
schoolId: 1
}, {
empId: 2,
name: 'BBB',
schoolId: 2
}];
var arrayTwo = [{
schoolId: 1,
schoolName: 'SchoolA'
}, {
schoolId: 2,
schoolName: 'SchoolB'
}];
var result = _.map(arrayOne, function(value, index) {
return _.extend({}, value, arrayTwo[index])
})
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
And one addition remark - with Lodash, this problem solves more concisely:
_.zipWith(arrayOne, arrayTwo, _.assign) // ==> returns what you need
Example with Lodash

Categories