I have an array of js objects which look like this:
var objArr = [
{"Country": "US", "City": "MyCity1", "2017-07-12": "1", "2017-07-13": "2"},
{"Country": "US", "City": "MyCity2", "2017-07-12": "2", "2017-07-13": "2"},
{"Country": "CN", "City": "MyCity1", "2017-07-12": "5", "2017-07-13": "7"},
{"Country": "CN", "City": "MyCity2", "2017-07-12": "5", "2017-07-13": "7"}
]
I wanna create a new array where the country is unique, but also the dates should be summed.
{"Country": "US", "2017-07-12": "3", "2017-07-13": "4"},
{"Country": "CN", "2017-07-12": "10", "2017-07-13": "14"}
^^^^ ^^^^ ^^^^
I have problems getting my head around it.
Do I have to filter first, reduce it somehow, remap it,... I've no idea to start?
Any help would be appreciated, thank you!
Use Array.reduce, check if an object with the current country exists, if it does, loop through the Object.keys to update the values, if not, push a new one :
EDIT : If you don't want City you can destructure it {City, ...curr}
var objArr = [
{ Country: "US", City: "MyCity1", "2017-07-12": "1", "2017-07-13": "2" },
{ Country: "US", City: "MyCity2", "2017-07-12": "2", "2017-07-13": "2" },
{ Country: "CN", City: "MyCity1", "2017-07-12": "5", "2017-07-13": "7" },
{ Country: "CN", City: "MyCity2", "2017-07-12": "5", "2017-07-13": "7" }
];
var result = objArr.reduce((acc, {City, ...curr}) => {
const ndx = acc.findIndex(e => e.Country === curr.Country);
if (ndx > -1) {
const [country, ...keys] = Object.keys(curr);
keys.forEach(k => {
acc[ndx][k] = +acc[ndx][k] + +curr[k];
});
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);
Use one forEach for array and go over each object date keys using forEach and build the one res object with unique keys as Country and accumulated values.
Use Object.values of res to get the array from res object.
Update: Fix to make sure always one type for dates which is number.
var objArr = [
{ Country: "US", City: "MyCity1", "2017-07-12": "1", "2017-07-13": "2" },
{ Country: "US", City: "MyCity2", "2017-07-12": "2", "2017-07-13": "2" },
{ Country: "CN", City: "MyCity1", "2017-07-12": "5", "2017-07-13": "7" },
{ Country: "CN", City: "MyCity2", "2017-07-12": "5", "2017-07-13": "7" }
];
const update = data => {
const res = {};
data.forEach(({ Country, City, ...dates }) => {
const item = res[Country] || { Country };
Object.keys(dates).forEach(date => {
item[date] = (item[date] || 0) + Number(dates[date]);
});
res[Country] = { ...item };
});
return Object.values(res);
};
console.log(update(objArr));
You can use reduce() to create an object to group elements and then use Object.values
var objArr = [
{"Country": "US", "City": "MyCity1", "2017-07-12": "1", "2017-07-13": "2"},
{"Country": "US", "City": "MyCity2", "2017-07-12": "2", "2017-07-13": "2"},
{"Country": "CN", "City": "MyCity1", "2017-07-12": "5", "2017-07-13": "7"},
{"Country": "CN", "City": "MyCity2", "2017-07-12": "5", "2017-07-13": "7"}
]
let keys = ["2017-07-12", "2017-07-13"];
const res = Object.values(objArr.reduce((ac, a) => {
if(!ac[a.Country]){
ac[a.Country] = {Country: a.Country};
}
keys.forEach(k => {
ac[a.Country][k] = (ac[a.Country][k] || 0) + Number(a[k]);
})
return ac;
}, {}))
console.log(res)
Related
I am looking to solve 2 problems here
Group the orders to create an items array based on based on orderNo
Include the tracking-information from the tracking array in tracking.json into the orders array.
So far I have only managed to get started with the grouping.
//orders.json
const orders = [
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "A",
"articleImageUrl": "watch.jpg",
"quantity": 1,
"product_name": "Watch"
},
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "B",
"articleImageUrl": "belt.jpg",
"quantity": 2,
"product_name": "Belt"
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": ""
}
];
//tracking.json
const tracking = [{
"tracking_number": "001",
"location": "",
"timestamp": "2018-04-01T00:00:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
},
{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
]
//expected output data.json
const data = [
{
"orderNo":"1",
"tracking_number":"001",
"courier":"FedEx",
"street":"1745 T Street Southeast",
"zip_code":"20020",
"city":"Louisville",
"destination_country":"USA",
"email":"test#test.com",
"articleNo":"A",
"articleImageUrl":"watch.jpg",
"quantity":"1",
"product_name":"Watch",
"items":[
{
"articleNo":"A",
"articleImageUrl":"watch.jpg",
"quantity":"1",
"product_name":"Watch"
},
{
"articleNo":"B",
"articleImageUrl":"belt.jpg",
"quantity":"2",
"product_name":"Belt"
}
],
"tracking":{
"tracking_number":"001",
"location":null,
"timestamp":"2018-04-01T00:00:00.000Z",
"status":"Scheduled",
"status_text":"Order processed",
"status_details":"The order has been processed."
}
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": "",
"items":[
],
"tracking":{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
}
]
const groupBy = key => array =>
array.reduce(
(objectsByKeyValue, obj) => ({
...objectsByKeyValue,
[obj[key]]: (objectsByKeyValue[obj[key]] || []).concat(obj)
}),
{}
);
const groupByOrders = groupBy('orderNo');
I am looking to get the data in the format shown in data.json
This is the current code along with the data
Code
Below is one possible way to achieve the target.
Code Snippet
const groupAndInclude = (base, delta) => {
const result = []; // result array
base.forEach( // iterate over the "orders"
({ // de-structure to directly access specific props
orderNo, tracking_number, articleNo,
articleImageUrl, quantity, product_name,
...rest // remaining props not directly-accessed
}) => {
const foundOrder = result.find( // find if "order" already in "result"
ob => ob.orderNo === orderNo
);
if (foundOrder) { // found a match, simply push "article"-info
if (articleNo.length > 0) { // push to "items" only if not "empty"
foundOrder.items.push({ // to the "items" array
articleNo, articleImageUrl, quantity, product_name
})
}
} else { // match not-found. Add new entry to "result"
const resObj = { // construct the result-object "resObj"
...rest, orderNo // using all relevant "order" props
};
if (articleNo.length > 0) { // do not add "empty" item
resObj.items = [{ // add "items" as an array
articleNo, articleImageUrl, quantity, product_name
}];
} else {
resObj.items = [];
};
const foundTracker = delta.find( // look for "tracking_number"
ob => ob.tracking_number === tracking_number
);
// if "tracking_number" found, add to result-object
if (foundTracker) resObj.tracking = {...foundTracker};
result.push(resObj); // push the result-object to the "result" array
}
}
);
return result; // explicitly return the "result" array
};
const orders = [{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "A",
"articleImageUrl": "watch.jpg",
"quantity": 1,
"product_name": "Watch"
},
{
"orderNo": "1",
"tracking_number": "001",
"courier": "FedEx",
"street": "1745 T Street Southeast",
"zip_code": 20020,
"city": "Louisville",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "B",
"articleImageUrl": "belt.jpg",
"quantity": 2,
"product_name": "Belt"
},
{
"orderNo": "2",
"tracking_number": "002",
"courier": "FedEx",
"street": "637 Britannia Drive",
"zip_code": 94591,
"city": "Vallejo",
"destination_country": "USA",
"email": "test#test.com",
"articleNo": "",
"articleImageUrl": "",
"quantity": "",
"product_name": ""
}
];
//tracking.json
const tracking = [{
"tracking_number": "001",
"location": "",
"timestamp": "2018-04-01T00:00:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
},
{
"tracking_number": "002",
"location": "",
"timestamp": "2018-04-06T05:58:00.000Z",
"status": "OrderProcessed",
"status_text": "Order processed",
"status_details": "The order has been processed."
}
];
console.log(groupAndInclude(orders, tracking));
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added in the snippet above.
You could take two objects as reference to same orderNo and tracking_number.
For adding an oder to the result set remove item properties and take a new object of this properties.
const
orders = [{ orderNo: "1", tracking_number: "001", courier: "FedEx", street: "1745 T Street Southeast", zip_code: 20020, city: "Louisville", destination_country: "USA", email: "test#test.com", articleNo: "A", articleImageUrl: "watch.jpg", quantity: 1, product_name: "Watch" }, { orderNo: "1", tracking_number: "001", courier: "FedEx", street: "1745 T Street Southeast", zip_code: 20020, city: "Louisville", destination_country: "USA", email: "test#test.com", articleNo: "B", articleImageUrl: "belt.jpg", quantity: 2, product_name: "Belt" }, { orderNo: "2", tracking_number: "002", courier: "FedEx", street: "637 Britannia Drive", zip_code: 94591, city: "Vallejo", destination_country: "USA", email: "test#test.com", articleNo: "", articleImageUrl: "", quantity: "", product_name: "" }],
tracking = [{ tracking_number: "001", location: "", timestamp: "2018-04-01T00:00:00.000Z", status: "OrderProcessed", status_text: "Order processed", status_details: "The order has been processed." }, { tracking_number: "002", location: "", timestamp: "2018-04-06T05:58:00.000Z", status: "OrderProcessed", status_text: "Order processed", status_details: "The order has been processed." }],
keys = ["articleNo", "articleImageUrl", "quantity", "product_name"],
items = {},
trackings = {},
result = [];
for (let order of orders) {
const item = {};
for (const key of keys) {
let value;
({ [key]: value, ...order } = order);
item[key] = value;
}
if (!items[order.orderNo]) result.push(items[order.orderNo] = { ...order, items: [] });
if (Object.values(item).some(Boolean)) items[order.orderNo].items.push(item);
trackings[order.tracking_number] = items[order.orderNo];
}
for (const transfer of tracking) trackings[transfer.tracking_number].tracking = transfer;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have the following data structure:
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
Using Ramda I would like to transforms it into:
const result = [
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "France",
"city": "Paris"
},
},
{
"firstName": "A",
"lastName": "B",
"address": {
"country": "Italy",
"city": "Rome"
},
},
];
You can use a converge function to fork the prop address and then join it with the main object for each address in the list:
/**
* R.pick could be replaced with R.omit
* to let you black list properties:
* R.omit(['address']); https://ramdajs.com/docs/#omit
**/
const createByAddress = R.converge(R.map, [
R.pipe(R.pick(['firstName', 'lastName']), R.flip(R.assoc('address'))),
R.prop('address'),
]);
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
console.log(createByAddress(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
My question is why "with Ramda"? I'm a founder of Ramda and a big fan, but it's just a tool, and unless this is a learning exercise for Ramda, it doesn't seem like there is any need to use it for this problem.
I would do it like this, using modern JS techniques:
const transform = ({address, ...rest}) =>
address .map (a => ({...rest, address: a}))
const data = {firstName: "A", lastName: "B", address: [{country: "France", city: "Paris"}, {country: "Italy", city: "Rome"}]}
console .log (
transform (data)
)
I am not sure if this will help you but if you want to generate multiple objects based on adress maybe this helps
const obj = {
firstName: "a",
lastName: "b",
adresses: [{
country: "France",
city: "Paris"
}, {
country: "Italy",
city: "Rome"
}]
};
adressAmount = obj.adresses.length;
const adressObjects = [];
for (let i = 0; i < adressAmount; i++) {
const {
adresses,
...objWithoutAdresses
} = obj;
objWithoutAdresses.adress = obj.adresses[i];
adressObjects.push(objWithoutAdresses);
}
console.log(adressObjects);
I found this pretty simple and short.
const data = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
],
};
let requiredData = data.address.map(element=>{
return {...data,address:element}
})
console.log(requiredData);
1) Create an empty dictionary
2) for loop the array and store index of each array in the dictionary as value
You can iterate the address array and create object as required
let obj = {
"firstName": "A",
"lastName": "B",
"address": [{
"country": "France",
"city": "Paris"
},
{
"country": "Italy",
"city": "Rome"
}
]
}
let newData = obj.address.map(function(item) {
return {
firstName: obj.firstName,
lastName: obj.lastName,
address: {
country: item.country,
city: item.city
}
}
});
console.log(newData)
I have the following flat array:
{ "State": "New York", "Name": "Jane", "Product": "Apple" },
{ "State": "New York", "Name": "Jill", "Product": "Banana"},
{ "State": "California", "Name": "Jill", "Product": "Apple" },
{ "State": "California", "Name": "Jill", "Product": "Banana"}
Is it possible to create a 2-level nested array (i.e., Name > nested State Array > nested Product Array)? It would look like as follows:
{
"Name": "Jill",
"States": [
{
"State": "California",
"Products": [
{
"Product": "Apple"
},
{
"Product": "Banana"
}
]
},
{
"State": "New York",
"Products": [
{
"Product": "Banana"
}
]
}
]
},
{
"Name": "Jane",
"States": [
{
"State": "New York",
"Products": [
{
"Product": "Apple"
}
]
}
]
}
I have been able to get one level nested (States). How would you nest the second level?
Here is a stackblitz: https://stackblitz.com/edit/angular-lu6zj2
this.grouped_data = this.data.reduce((data, item) => {
data[item.Name] = data[item.Name] || { Name: item.Name, States: []}
data[item.Name].States.push(item)
return data;
}, {})
let data = [
{ "State": "New York", "Name": "Jane", "Product": "Apple" },
{ "State": "New York", "Name": "Jill", "Product": "Banana"},
{ "State": "California", "Name": "Jill", "Product": "Apple" },
{ "State": "California", "Name": "Jill", "Product": "Banana"}
];
let grouped = data.reduce((p, n) => {
// Create the Lady
if (!p[n.Name]) p[n.Name] = { States: [] };
// Check if the state exists, if not create it, then push product into it
if (!p[n.Name].States.some(state => state.State === n.State)) {
p[n.Name].States.push({ State: n.State, Products: [n.Product] });
} else {
!p[n.Name].States.find(state => state.State === n.State).Products.push(n.Product);
}
return p;
}, {});
console.log(grouped);
After that you can also remove duplicated products if you want to. I'll let you deal with it !
EDIT I didn't respect your model, what a dumbass am I ... Here it is :
let data = [
{ "State": "New York", "Name": "Jane", "Product": "Apple" },
{ "State": "New York", "Name": "Jill", "Product": "Banana"},
{ "State": "California", "Name": "Jill", "Product": "Apple" },
{ "State": "California", "Name": "Jill", "Product": "Banana"}
];
let grouped = data.reduce((p, n) => {
// Create the Lady
if (!p.some(lady => lady.Name === n.Name)) p.push({ Name: n.Name, States: [] });
let lady = p.find(lady => lady.Name === n.Name);
// Check if the state exists, if not create it, then push product into it
if (!lady.States.some(state => state.State === n.State)) {
lady.States.push({ State: n.State, Products: [n.Product] });
} else {
lady.States.find(state => state.State === n.State).Products.push(n.Product);
}
return p;
}, []);
console.log(grouped);
Original data looks like that:
let AddressesBook = [
{
"userName": "Jay12",
"doorNumber": "1512",
"cityID": 19,
"city": "London",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "2003",
"cityID": 14,
"city": "York",
"countryID": 1,
"universe": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "435",
"cityID": 31,
"city": "Washington",
"countryID": 2,
"universe": "USA",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "1123",
"cityID": 18,
"city": "Oxford",
"countryID": 1,
"universe": "UK",
"houseType": "private"
}
];
i was mapping the data hierarchy by relevant unique ID using Lodash and
a suppurated dictionary:
function nestMaker(list, order) {
if (_.isEmpty(order)) return [];
let groups = _.groupBy(list, _.first(order));
return _.map(groups, (children, key) => {
let group = {};
group[_.first(order)] = key;
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
let hierarchical = nestMaker(AddressesBook, [
"countryID",
"cityID",
"houseType",
"doorNumber"]
);
it works fine, but i would like to have the name relevant to the id in each level of the object.
unfortunately you can't use _.groupBy on two keys. i was thinking about using _.unionWith separately from the first iteration but i couldn't find a way to use it recursively omitting the unnecessary data.
expected output:
let output =
[
{
"countryID": "1",
"country": "UK",
"data": [
{
"cityID": "14",
"city": "York",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "2003"
}
]
}
]
},
{
"cityID": "18",
"city": "Oxford",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "1123"
}
]
}
]
},
{
"cityID": "19",
"city": "London",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "1512"
}
]
}
]
}
]
},
{
"countryID": "2",
"country": "USA",
"data": [
{
"cityID": "31",
"city": "Washington",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "435"
}
]
}
]
}
]
}
];
You can get the 1st item in the group, and extract the name (country, city) from the item:
const AddressesBook = [{"userName":"Jay12","doorNumber":"1512","cityID":19,"city":"London","countryID":1,"country":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"2003","cityID":14,"city":"York","countryID":1,"country":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"435","cityID":31,"city":"Washington","countryID":2,"country":"USA","houseType":"private"},{"userName":"Jay12","doorNumber":"1123","cityID":18,"city":"Oxford","countryID":1,"country":"UK","houseType":"private"}];
const nestMaker = (list, order) => {
if (_.isEmpty(order)) return [];
const idKey = _.first(order);
const nameKey = idKey.replace('ID', '');
let groups = _.groupBy(list, idKey);
return _.map(groups, (children, key) => {
const group = {};
const child = _.first(children);
group[idKey] = key;
if(_.has(child, nameKey)) group[nameKey] = child[nameKey];
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
const hierarchical = nestMaker(AddressesBook, [
"countryID",
"cityID",
"houseType",
"doorNumber"
]);
console.log(hierarchical);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If the id and the name keys are doesn't follow the same pattern, you can explicitly state them as entry in the order:
const AddressesBook = [{"userName":"Jay12","doorNumber":"1512","cityID":19,"city":"London","countryID":1,"universe":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"2003","cityID":14,"city":"York","countryID":1,"universe":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"435","cityID":31,"city":"Washington","countryID":2,"universe":"USA","houseType":"private"},{"userName":"Jay12","doorNumber":"1123","cityID":18,"city":"Oxford","countryID":1,"universe":"UK","houseType":"private"}];
const nestMaker = (list, order) => {
if (_.isEmpty(order)) return [];
const entry = _.first(order);
const [idKey, nameKey] = Array.isArray(entry) ? entry : [entry];
let groups = _.groupBy(list, idKey);
return _.map(groups, (children, key) => {
const group = {};
const child = _.first(children);
group[idKey] = key;
if(_.has(child, nameKey)) group[nameKey] = child[nameKey];
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
const hierarchical = nestMaker(AddressesBook, [
["countryID", "universe"],
["cityID", "city"],
"houseType",
"doorNumber"
]);
console.log(hierarchical);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
This is a bit manual but does the job.
let AddressesBook = [{
"userName": "Jay12",
"doorNumber": "1512",
"cityID": 19,
"city": "London",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "2003",
"cityID": 14,
"city": "York",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "435",
"cityID": 31,
"city": "Washington",
"countryID": 2,
"country": "USA",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "1123",
"cityID": 18,
"city": "Oxford",
"countryID": 1,
"country": "UK",
"houseType": "private"
}
];
database = []
AddressesBook.forEach(a => {
doesExist = database.some(d => (d.countryID == a.countryID))
if (doesExist) {
let instance = database.filter(d => d.countryID == a.countryID)[0]
instance.data.push({
"cityID": a.cityID,
"city": a.city,
"data": [{
"houseType": a.houseType,
"data": [{
"doorNumber": a.doorNumber
}]
}]
})
} else {
database.push({
"countryID": a.countryID,
"country": a.country,
"data": [{
"cityID": a.cityID,
"city": a.city,
"data": [{
"houseType": a.houseType,
"data": [{
"doorNumber": a.doorNumber
}]
}]
}]
})
}
})
console.log(database)
For example, I have an array like this.
[{
"Country": "USA", "Nickname": "John"
}, {
"Country": "Japan", "Nickname": "Grace"
}, {
"Country": "Japan", "Nickname": "Mark"
}, {
"Country": "Japan", "Nickname": "Paul"
}, {
"Country": "China", "Nickname": "Sansa"
}, {
"Country": "USA", "Nickname": "Clint"
}, {
"Country": "China", "Nickname": "James"
}, {
"Country": "Japan", "Nickname": "Mary"
}]
I want my array to look like this..
[{
"Country": "USA", "Nickname": "John , Clint"
}, {
"Country": "Japan", "Nickname": "Grace , Mark , Paul , Mary"
}, {
"Country": "China", "Nickname": "Sansa, James"
}]
I want to merge the nicknames by their country. What should I do?
Here is an easy example done by object and array.
Next time you can totally try it yourself, dude.
var arr = [{
"Country": "USA", "Nickname": "John"
}, {
"Country": "Japan", "Nickname": "Grace"
}, {
"Country": "Japan", "Nickname": "Mark"
}, {
"Country": "Japan", "Nickname": "Paul"
}, {
"Country": "China", "Nickname": "Sansa"
}, {
"Country": "USA", "Nickname": "Clint"
}, {
"Country": "China", "Nickname": "James"
}, {
"Country": "Japan", "Nickname": "Mary"
}]
var obj = {};
var new_arr = [];
for(var i=0;i<arr.length;i++){
var d = arr[i];
if(!obj[d['Country']])
obj[d['Country']] = [];
obj[d['Country']].push(d['Nickname']);
}
for(var key in obj){
new_arr.push({
"Country": key,
"Nickname": obj[key].join(' , ')
})
}
console.log(new_arr);
let arr = [{"Country": "USA", "Nickname": "John"}, {"Country": "Japan", "Nickname": "Grace"}, {"Country": "Japan", "Nickname": "Mark"}, {"Country": "Japan", "Nickname": "Paul"}, {"Country": "China", "Nickname": "Sansa"}, {"Country": "USA", "Nickname": "Clint"}, {"Country": "China", "Nickname": "James"}, {"Country": "Japan", "Nickname": "Mary"}];
let answer = [];
arr.forEach(x=>{
if(!answer.some(y => y.Country === x.Country)){
answer.push(x);
}else{
let country = answer.find(y => y.Country === x.Country);
country.Nickname = country.Nickname.concat(`, ${x.Nickname}`);
}
});
console.log(answer)
Use some to check existence in another Array, if not exist, push the item to new array, if exist, grab it and append the nickname.
I faced the same issue a while a ago and this how did and you can achieve this by simply using this:
let result = [];
arr.forEach(function(obj) {
let id = obj.Country;
if(!this[id]) {
result.push(this[id] = obj);
} else {
this[id].Nickname += `, ${obj.Nickname}`;
}
}, Object.create(null));
console.log(result);
In the result you will get your desired result... and I have tested it...
Before posting the question you should try it yourself... Everyone will advice you the same... You are still new here I think but for the next time you should try first and then ask where you stuck...
You can use reduce to group the array into an object. Use Object.entries to convert the object into an array. Use map to format the array.
var arr = [{"Country":"USA","Nickname":"John"},{"Country":"Japan","Nickname":"Grace"},{"Country":"Japan","Nickname":"Mark"},{"Country":"Japan","Nickname":"Paul"},{"Country":"China","Nickname":"Sansa"},{"Country":"USA","Nickname":"Clint"},{"Country":"China","Nickname":"James"},{"Country":"Japan","Nickname":"Mary"}];
var result = Object.entries(arr.reduce((c, v) => {
c[v.Country] = c[v.Country] || [];
c[v.Country].push(v.Nickname);
return c;
}, {})).map(([k, v]) => ({"Country": k,"Nickname": v.join(' , ')}));
console.log(result);