Adding an array as a new key-value pair - javascript

I have an existing array which contains key-value pairs for a series of items:
resultsArray = [
{
parkName: "Central Park",
owner: "NYC"
},
{
parkName: "Patterson Park",
owner: "Baltimore"
}
]
I'd like to add an additional key-value pair to each item where the value is an array of amenities. For example: if Central Park includes a dog park, jogging trail, and basketball courts, and Patterson Park includes a baseball field and a rec center, when the amenities were added to the array, the resultsArray would now look like:
resultsArray = [
{
parkName: "Central Park",
owner: "NYC",
amenities: "Dog Park", "Jogging Trail", "Basketball Courts"
},
{
parkName: "Patterson Park",
owner: "Baltimore",
amenities: "Baseball Fields", "Recreation Center"
}
]
I'm relatively new to Javascript, but I've successfully created an array of amenities for each of the parks. I then tried to add each amenityArray as follows:
resultsArray.push({
amenities: amenityArray
});
However, this didn't give me what I wanted.
Can someone demonstrate how I would add the amenityArray as a key-value pair for each of the parks?

For each object in resultsArray, add the corresponding amenity.
for (let i = 0; i < resultsArray.length; i++) {
resultsArray[i][i]['amenities'] = amenityArray[i];
}
A more verbose version would be
for (let i = 0; i < resultsArray.length; i++) {
let result = resultsArray[i]; // i is an index
let innerResult = result[i]; // i is a key
innerResult['amenities'] = amenityArray[i];
}

Iterate the array and add a new key-value pair in the inner objects.
Note: Picked the amenities dynamically.
resultsArray = [{ 0: { parkName: "Central Park", owner: "NYC" } }, { 1: { parkName: "Patterson Park", owner: "Baltimore" } }];
amenities = { "0": "X Park, Y Park, Z Park", "1": "A Park, B park, C Park" };
[...resultsArray].forEach(token => {
Object.keys(token).forEach(key => token[key]['amenities'] = amenities[key]);
})
console.log(resultsArray);

You can use map for this:
const newArray = resultsArray.map((item, i) => {
item[i].amenities = amenityArray[i];
return item;
});
Also your array structure looks weird, you should consider removing those redundant nested objects, and then it will be easier to iterate:
resultsArray = [{
parkName: "Central Park",
owner: "NYC"
},
{
parkName: "Patterson Park",
owner: "Baltimore"
}
]
const newArray = resultsArray.map((item, i) => {
item.amenities = amenityArray[i];
return item;
});

You can use .forEach() to loop through the array and set each item depend on index:
var resultsArray = [{parkName: "Central Park",owner: "NYC"},{parkName: "Patterson Park", owner: "Baltimore"}]
var amenityArray = [["Dog Park", "Jogging Trail", "Basketball Courts"], ["Baseball Fields", "Recreation Center"]];
resultsArray.forEach((val, index) => {val.amenities = amenityArray[index]})
console.log(resultsArray)

Related

How to Perform 2 join operation on an Object array?

const rows = [
["Name", "City", "Info"],
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
let csvContent = rows.map(e => e.join(",")).join("\n");
Similarly how can I implement the same on an Object array for example
const rows = [
{name:"FirstName", city:"City", info:"Info"},
{name:"LastName", city:"City", info:"Info"},
];
First you can Array#reduce it, saving the Object.keys as the first header row, then creating the array structure. Finally map all that just like your first example.
const rows2 = [{
name: "FirstName",
city: "City",
info: "Info"
},
{
name: "LastName",
city: "City",
info: "Info"
},
];
let csvContent2 = rows2.reduce((b, a, i) => {
if (i === 0) b.push(Object.keys(a))
return b.concat([Object.values(a)]);
}, []).map(e => e.join(",")).join("\n")
console.log(csvContent2);

Map one property from object array to another object in different object array

I have two object array. let's say Shop array & Country array. An Shop array's one object has {id:01,name:'name of the shop',countryCode:'USA'} and Country array's one object has {code:'USA', country:'United States of America'} i want to map shop's object the country code to country's object country an create new object array.in new object array, one object should look like this.
{id:01,name:'name of the shop',countryCode:'USA',country:'United States of America'}
what is the most optimized way to do this
let shopArray=[{id:01,name:'name of the shop',countryCode:'USA'}]
let countryArray=[{code:'USA', country:'United States of America'}]
let mapedShopArray=shopArray.map(eachShop=>{
for(let eachCountry of countryArray){
if(eachCountry.code==eachShop.countryCode){
eachShop.country =eachCountry.country;
break;
}
}
return eachShop;
})
console.log(mapedShopArray)
You can do this
let shopArrayObj = [{ id: 01, name: "shop1", countryCode: 'USA' },
{ id: 02, name: "shop2", countryCode: 'US' },
{ id: 03, name: "shop3", countryCode: 'ENG' }]
let countryArrayObj = [{ code: 'USA', country: 'United States of America' },
{ code: 'ENG', country: 'England' }]
let finalArrayOb = []
shopArrayObj.map(shop => {
countryArrayObj.map(country => {
if (country.code === shop.countryCode) {
let obj = { ...shop, ...country, }
delete obj.code
finalArrayOb.push(obj)
}
})
})
console.log(finalArrayOb)
You could do something like this.
let shopArr = [{id:01,name:'name of the shop',countryCode:'USA'}];
let countryArr = [{code:'USA', country:'United States of America'}];
let newArr = shopArr.map((shop) => {
return {...shop, country: countryArr.find(country => {country.code === shop.countryCode}).country};
});
You can do like this:
let country1 = [{code:'USA', country:'United States of America'}]
let shop1 = [{id:01,name:'name of the shop',countryCode:'USA'}]
country1.forEach((item1) => {
shop1.forEach((item2) => {
if(item1.code === item2.countryCode) {
arr.push({'id': item2.id, 'name': item2.name, 'countryCode': item2.countryCode, 'country': item1.country})
}
})
})
Hope this helps.
If you can restructure Country as an object, instead of an array, we will be able to achieve the result using single for loop. Working code is given below.
var country = {
"USA": "United States of America",
"IN": "India",
"UAE": "United Arab Emirates",
"UK": "United Kingdom"
}
var shopArray = [{id:01,name:'name of the shop',countryCode:'USA'}, {id:02,name:'name of another shop',countryCode:'UK'}]
for(var i=0;i<shopArray.length; i++){
var countryCode = shopArray[i].countryCode;
shopArray[i].country = country[countryCode];
}
console.log(shopArray)
This code will actually modify original shopArray, instead of giving a new array.
You can do it as follows.
const array1 = [{ id: 1, name:'My Shop', countryCode:'USA' }, { id: 2, name:'My Shop2', countryCode:'UK' }];
const array2 = [{ code:'USA', country:'United States of America' }, { code:'UK', country:'United Kingdom' }];
let myArray = [];
array1.forEach(item1 => {
array2.forEach(item2 => {
if (item1.countryCode === item2.code) {
let obj = {...item1, country: item2.country };
myArray.push(obj)
}
});
});
Demo

Javascript object flatten to array

I have been trying today to flatten an object array. I cannot achieve what I need, I need to access to inner most element( 1st ) to the outer most element ( 4th ) here is a sample of the data there are some null values which might make it complex:
{
"School":"Arsenal 2011", //4th Element in new array
"Group":{
"Name":"Previous", //3rd Element in new array
"ParentGroup":{
"Name":"Arsenal", //2nd Element in new array
"ParentGroup":{
"Name":"USA", //1st Element in new array
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}
The output array I would like is:
array[0] = { "USA","Arsenal","Previous" }
array[x] = for all the other data
How would I do this in Javascript?
I have added a plunker if it helps
https://plnkr.co/edit/LNlHArCob4Bix8VYHFwI?p=preview
Thanks
Use Array.prototype.map and _.get() to handle null scenarios
const data = [{
"School":"Arsenal 2011", //4th Element in new array
"Group":{
"Name":"Previous", //3rd Element in new array
"ParentGroup":{
"Name":"Arsenal", //2nd Element in new array
"ParentGroup":{
"Name":"USA", //1st Element in new array
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}];
const formatted = data.map(item => {
return [
_.get(item, 'Group.ParentGroup.ParentGroup.Name'),
_.get(item, 'Group.ParentGroup.Name'),
_.get(item, 'Group.Name'),
_.get(item, 'School')
];
});
console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
You could take an iterative check for the nested properties.
var data = [{ School: "Arsenal 2011", Group: { Name: "Previous", ParentGroup: { Name: "Arsenal", ParentGroup: { Name: "USA", ParentGroup: null } } }, GroupDisplayText: null, Publisher: "Abbot", PublishedDate: "2011", PublishersWebsite: "http://google.com/USA/ADW%202011/Arsenal%202011.pdf" }, { School: "New York 2000", Group: { Name: "New York", ParentGroup: { Name: "USA", ParentGroup: null } }, GroupDisplayText: null, Publisher: "DoE", PublishedDate: "2000", PublishersWebsite: "http://google.com/USA/New York%202000%20Tables.pdf" }],
result = data.map(({ School, Group: ParentGroup }) => {
var array = [School];
while (ParentGroup) {
array.unshift(ParentGroup.Name);
({ ParentGroup } = ParentGroup);
}
return array;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If it was only one level deep, [_.pluck()] would work.(https://lodash.com/docs/3.10.1#pluck)
Gets the property value of path from all elements in collection.
From their example:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
_.pluck(users, 'user');
// => ['barney', 'fred']
For the nested elements, you can accomplish it with a _.forEach()
Iterates over elements of collection invoking iteratee for each
element.
Loop through the items and in the iteratee function just add the appropriate elements to their respective arrays.

Create Multidimensional array of [key,value] with key unique count as value from Array of JSON Object

Currently i have array of json object returned by server
data: [
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
},
...more json data
];
I have to create a count of values in Array like below for representation for google charts:
[
//designation count
["ASE", 2],
["SE", 2]
],
[
//project count
["ABC", 1],
["DEF", 2]
],
//and similarly others.
How can i count the no of occurances of the keys with the values of previous occurance intact,
and also in ['key','value'] of key being the unique occurance of data and value being the no of occurance ???
Iterate over the data with reduce to create an object grouped by type. Here's a reusable function - just pass in the data and the type.
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCount(data, type) {
// `map` out the data by type
const typeArr = data.map((obj) => obj[type]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
return Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
}
console.log(getCount(data, 'designation'));
console.log(getCount(data, 'project'));
Further reading
reduce
Object.values
Alternatively, if you wanted to do this in one operation and return an object containing the grouped information, you could use another reduce to iterate over the main data keys:
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCounts(data) {
// Grab the data keys. It assumes that each object in
// the array has the same keys
const keys = Object.keys(data[0]);
// Using `reduce` iterate over the keys to build
// up an object that groups the results from the inner
// `reduce` operation by key
return keys.reduce((out, key) => {
// `map` out the data by type
const typeArr = data.map((obj) => obj[key]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
out[key] = Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
// Return the `out` object for the next iteration
return out;
}, {});
}
console.log(getCounts(data));
Lot's of ways to do this. Here is a simple way (could be cleaned up, but just trying to demo):
View on JSFiddle
const data = [{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
}
];
const designations = [],
projects = [];
for (const record of data) {
// Count designations
if (!designations[record.designation]) {
designations[record.designation] = 0;
}
designations[record.designation] = designations[record.designation] + 1;
// Count projects
if (!projects[record.project]) {
projects[record.project] = 0;
}
projects[record.project] = projects[record.project] + 1;
}
// Merge sets
const final = [designations, projects];
console.log(final);
const data = [
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
}
];
const result = data.reduce((acc,cur) => {
for(let k in cur) {
if(!acc[k]) {
acc[k] = [[cur[k], 1]];
} else {
const idx = acc[k].findIndex(e => e[0] === cur[k]);
if(idx !== -1) {
acc[k][idx][1]++
} else {
acc[k].push([cur[k], 1])
}
}
}
return acc;
}, {});
console.log(result)

Extract properties from deleted/duplicated objects then assign to other objects

I need a little help here, y have this array:
[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:14}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:3}
{Code:13953, Country:699, Name:"OZ", codeProduct:12}
....
]
And I need to convert to this:
[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:"14, 1, 3" }
{Code:13953, Country:699, Name:"Polo Club", codeProduct:12}
]
I have no problem removing the duplicate objects, and getting the values of those delted objects.
var prodArray = [];
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for(var i = 0; i < len; i++) {
var item = a[i].Codigo;
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = a[i];
}else{
prodArray.push({Code:item, codeProduct:a[i].TipoProductoCodigo});
}
}
return out;
}
this return a new array of objects whitout the repited values and add to a new array prodArray the properties of deleted ones.
// out return this:
[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:"14, 1, 3" }
{Code:13953, Country:699, Name:"Polo Club", codeProduct:12}
]
and prodArr return this:
[
{Code:13952, codeProduct:1}
{Code:13952, codeProduct:3}
]
But how do i set the properties in prodArray in to the new one array that holds the no duplicate objects?.
Hope i have been clear
You could use a hash table as reference to the Code.
var data = [{ Code: 13938, Country: 699, Name: "Crocs", codeProduct: 1 }, { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 14 }, { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 1 }, { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 3 }, { Code: 13953, Country: 699, Name: "OZ", codeProduct: 12 }],
grouped = [];
data.forEach(function (a) {
if (!this[a.Code]) {
this[a.Code] = { Code: a.Code, Country: a.Country, Name: a.Name, codeProduct: a.codeProduct };
grouped.push(this[a.Code]);
return;
}
this[a.Code].codeProduct += ', ' + a.codeProduct;
}, Object.create(null));
console.log(grouped);
I'll try my best to answer this without fully understanding what you're attempting to do...
So you have your duplicate values in prodArray, great. Now you want them to be placed back into the array you just removed them from? Sure. To append an element to the end of an array, you use the push method.
I'm assuming the thing that you're caught up on is grabbing those missing JSON properties, Country and Name, and adding them back to the elements in prodArray. But since we know that Code is the same, we can use that to find the "missing" values. So here's how I'd do it, assuming a is your original array:
for (var i in prodArray) {
// find the duplicate in the orginal array
for (var j in a) {
if (a[j].Code == prodArray[i].Code) {
// found it, now append into a
a.push(a[j]);
break;
}
}
}
Am I close?

Categories

Resources