I am working on an angular application. I have two arrays as follows:
array1 = [
{
Name: "Jack",
Id: "1",
Location: "UK"
},
{
Name: "Rose",
Id: "2",
Location: "USA"
},
{
Name: "Mary",
Id: "3",
Location: "India"
}
];
array2 = [
{
Name: "Raj",
Id: "5",
Location: "UK"
},
{
Name: "John",
Id: "2",
Location: "Germany"
},
{
Name: "Maria",
Id: "3",
Location: "Canada"
}
];
I want a resultant array such that If "Id" of any element of array1 matches "Id" of any element in array2, then whole data for that particular "Id" should be replaced in array2. So my resulArray will look as follows:
resultArray = [
{
Name: "Raj",
Id: "5",
Location: "UK"
},
{
Name: "Rose",
Id: "2",
Location: "USA"
},
{
Name: "Mary",
Id: "3",
Location: "India"
}
];
So Id= 2 and Id =3 of array 1 matches in array2, so data of Id=2 and Id=3 in array2 are replaced by that of array1. How can I do it?
You need map and find here. You can put an OR condition that if value is present in array1 if so then will pick the object from array1 otherwise the current object will be chosen.
var array2=[ { "Name": "Raj", "Id": "5", "Location": "UK" }, { "Name": "John", "Id": "2", "Location": "Germany" }, { "Name": "Maria", "Id": "3", "Location": "Canada" }];
var array1= [{ "Name": "Jack", "Id": "1", "Location": "UK"},{ "Name": "Rose", "Id": "2", "Location": "USA"},{ "Name": "Mary", "Id": "3", "Location": "India"}];
var result = array2.map(p=>(array1.find(k=>k.Id==p.Id) || p));
console.log(result);
I hope this helps.
You can use reduce and find function for your requirement
array2.reduce((acc, c) => {
var existed = array1.find(a=>a.Id == c.Id);
if(existed){
c.Name = existed.Name;
}
return c;
}, [])
var array1= [
{
"Name": "Jack",
"Id": "1",
"Location": "UK"
},
{
"Name": "Rose",
"Id": "2",
"Location": "USA"
},
{
"Name": "Mary",
"Id": "3",
"Location": "India"
}
]
var array2=[
{
"Name": "Raj",
"Id": "5",
"Location": "UK"
},
{
"Name": "John",
"Id": "2",
"Location": "Germany"
},
{
"Name": "Maria",
"Id": "3",
"Location": "Canada"
}
];
array2.reduce((acc, c) => {
var existed = array1.find(a=>a.Id == c.Id);
if(existed){
c.Name = existed.Name;
}
return c;
}, [])
console.log(array2)
Related
Distinct array of objects as like below; i want to get unique array of objects.
Example Array:
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]
Expected Output:
const data = [ { "name": "abc", age: "31", project: "Java" },{ "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }]
This approach enforces a consistent key order, and uses JSON.stringify on each object to test for uniqueness.
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]
const result = [...new Set(data.map(i=>JSON.stringify(Object.fromEntries(
Object.entries(i).sort(([a],[b])=>a.localeCompare(b))))
))].map(JSON.parse)
console.log(result)
let unique = [...new Set(data.map(i => JSON.stringify(i)))].map(i => JSON.parse(i));
As per your data, project property is containing dynamic values. Hence, You can filtered out the duplicates with in a single line of code by using Array.filter() method.
Live Demo :
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }];
const uniq = {};
var arrFiltered = data.filter(obj => !uniq[obj.project] && (uniq[obj.project] = true));
console.log(arrFiltered);
From
[
{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
]
to this:
{
"Jack" :{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
"Mary" : {
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
"John": {
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
}
You can use .map() and Object.fromEntries().
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
var result = Object.fromEntries(data.map(el => [el.name, el]));
console.log(result);
1. using forEach :
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
var result = {};
data.forEach(function(val) {
result[val["name"]] = val;
});
console.log(result);
2. Using object.assign and map:
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
let dictionary = Object.assign({}, ...data.map((x) => ({
[x.name]: x
})));
console.log(dictionary);
You can use an array reduce method.
Array.prototype.reduce()
const test = [
{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
const results = test.reduce((obj, props) => {
obj[props.name] = props;
return obj;
} , {});
console.log(results);
You need to take your data, let's say it's stored in the data variable, and reduce() it with this one-liner:
const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {} );
const data = [
{
id: '0001',
name: 'Jack',
completeName: 'Jack Smith',
},
{
id: '0002',
name: 'Mary',
completeName: 'Mary Jackson',
},
{
id: '0003',
name: 'John',
completeName: 'John Doe',
},
];
const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {});
console.log(output);
I wanted to get the difference between two arrays which is nested.
let firstArray = {
"family": "BLUE",
"globalThreshold": "2.0",
"levelData": [
{
"name": "India",
"value": "4.0",
"count": [
{
"id": "21",
"countName": "ABC",
"countThreshold": "7.0"
},
{
"id": "22",
"workscopeName": "DEF",
"countThreshold": "4242"
}
]
},
{
"name": "FEDERAL EXPRESS CORPORATION",
"value": "1.0",
"count": [
{
"id": "5",
"countName": "ABC",
"countThreshold": "2.0"
},
{
"id": "6",
"countName": "DEF",
"countThreshold": "3.0"
}
]
}
]
}
let changedArray= {
"family": "BLUE",
"globalThreshold": "2.0",
"levelData": [
{
"name": "India",
"value": "5",
"count": [
{
"id": "21",
"countName": "ABC",
"countThreshold": "7.0"
},
{
"id": "22",
"workscopeName": "DEF",
"countThreshold": "4242"
}
]
},
{
"name": "FEDERAL EXPRESS CORPORATION",
"value": "1.0",
"count": [
{
"id": "5",
"countName": "ABC",
"countThreshold": "60"
},
{
"id": "6",
"countName": "DEF",
"countThreshold": "3.0"
}
]
}
]
}
Expected result:
let finalArray = {
"family": "BLUE",
"globalThreshold": "2.0",
"levelData": [
{
"name": "India",
"value": "5",
"count": []
},
{
"name": "FEDERAL EXPRESS CORPORATION",
"value": "1.0",
"count": [
{
"id": "5",
"countName": "ABC",
"countThreshold": "60"
}
]
}
]
}
I would like to track the diffference based on the value property inside 'levelData' array and countThreshold inside count array.
i tried repeating two arrays in for loop but was not able to repeat Any simultaneously as its nested.Do let me know any quick approach..
Thanks
Try using map to iterate for each levelData finding their respective in firstArray by name then filter by matching its properties:
let firstArray={"family":"BLUE","globalThreshold":"2.0","levelData":[{"name":"India","value":"4.0","count":[{"id":"21","countName":"ABC","countThreshold":"7.0"},{"id":"22","workscopeName":"DEF","countThreshold":"4242"}]},{"name":"FEDERAL EXPRESS CORPORATION","value":"1.0","count":[{"id":"5","countName":"ABC","countThreshold":"2.0"},{"id":"6","countName":"DEF","countThreshold":"3.0"}]}]};
let changedArray={"family":"BLUE","globalThreshold":"2.0","levelData":[{"name":"India","value":"5","count":[{"id":"21","countName":"ABC","countThreshold":"7.0"},{"id":"22","workscopeName":"DEF","countThreshold":"4242"}]},{"name":"FEDERAL EXPRESS CORPORATION","value":"1.0","count":[{"id":"5","countName":"ABC","countThreshold":"60"},{"id":"6","countName":"DEF","countThreshold":"3.0"}]}]}
var arr = changedArray.levelData.map(ele => {
var count = firstArray.levelData.find(x => x.name == ele.name).count;
ele.count = ele.count.filter(x => !count.some(y => x.id == y.id && x.countThreshold == y.countThreshold));
return ele;
})
console.log(arr);
I have a set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below.
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }]
var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" }],
"5": [{ "Id": "5", "name": "zzz", "age": "59" }]}]
You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need
var data= [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }];
console.log(data.reduce(function(result, current) {
result[current.Id] = result[current.Id] || [];
result[current.Id].push(current);
return result;
}, {}));
Try
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }], output;
output = [origObj.reduce((a,c) => (a[c.Id]=(a[c.Id]||[]).concat(c),a) ,{})];
console.log(output);
I have following JSON structure:
{
"shops": {
"categories": {
"cat_1": {
"id": "1",
"label": "Men's Fashions",
"Brands": [{
"id": "2",
"name": "Smith"
}]
},
"cat_2": {
"id": "2",
"label": "Restaurants",
"Brands": [{
"id": "3",
"name": "KFC"
}, {
"id": "4",
"name": "SUBWAY"
}, {
"id": "5",
"name": "MLD"
}, {
"id": "6",
"name": "THAI"
}]
},
"cat_3": {
"id": "3",
"label": "Specialty Shops",
"Brands": [{
"id": "7",
"name": "BODY SHOP"
}]
}
}
}
}
I'd like to achieve something like this:
[{
"categoryid": "1",
"id": "2",
"label": "Men's Fashions",
"name": "Smith"
},
{
"categoryid": "2",
"id": "3",
"label": "Restaurants",
"name": "KFC"
},
{
"categoryid": "2",
"id": "4",
"label": "Restaurants",
"name": "SUBWAY"
},
{
"categoryid": "2",
"id": "5",
"label": "Restaurants",
"name": "MLD"
},
{
"categoryid": "2",
"id": "6",
"label": "Restaurants",
"name": "THAI"
}, {
"categoryid": "3",
"id": "7",
"label": "Specialty Shops",
"name": "BODY SHOP"
},
]
Is there an elegant way to achieve it using underscore?
I tried to use nested _.each() to do that, but feel there might be something better.
generateArray: function(obj) {
var newResult = [];
_.each(obj.categories, function(c) {
_.each(c.Brands, function(d) {
newResult.push({
"categoryid": c.id,
"id": d.id,
"label": c.label,
"name": d.name
});
});
});
return newResult;
}
Anyone can advise me which way is more efficiency at running time?
mine or #Artyom Neustroev or #Anthony Chu ?
You don't really need underscore for that task. Use simple for .. in .. and for (...) loops:
var json = {...};
var result = [];
for (var catKey in json.shops.categories) {
var currentCategory = json.shops.categories[catKey];
for (var i = 0; i < currentCategory.Brands.length; i++) {
var currentBrand = currentCategory.Brands[i];
result.push({
categoryid: currentCategory.id,
label: currentCategory.label,
id: currentBrand.id,
name: currentBrand.name
});
}
}
Fiddle here
Instead of each()'s, here's a way to do it with map()'s...
var output = _.chain(input.shops.categories)
.map(function (category) {
return _(category.Brands).map(function (brand) {
return { categoryId: category.id,
id: brand.id,
label: category.label,
name: brand.name
};
});
}).flatten().value();
JSFIDDLE