How to merge objects using javascript - javascript

I am trying to create a json object similar to the below:
[
{
"name":"aaa_aaaurf",
"region":"F&R",
"checkins":[[1,0],[2,0],[3,0],[4,3],[5,0],[6,0],[7,0],[8,3],[9,0],[10,0],[11,0],[12,0]],
"teamsize":[[1,0],[2,0],[3,0],[4,3],[5,0],[6,0],[7,0],[8,1],[9,0],[10,0],[11,0],[12,0]],
"Checkintimes":[[1,0],[2,0],[3,0],[4,184],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,0],[12,0]]
},
{
"name":"aaa_accessservices",
"region":"F&R",
"checkins":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,27],[12,12]],
"teamsize":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,11],[12,11]],
"Checkintimes":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],[11,10],[12,12]]
}]
I have written the script using d3 but the object is getting overwritten with the latest one.How to merge the object array to get the json?
Following is the code:
var dataset;
var teamsize={};
var repository;
var sbu;
var index=0;
var teamsizearray = [];
var checkinsarray = [];
var checkintimesarray = [];
var ConsData = {};
var MergeData = {};
var tempData={};
d3.csv("bubblechart.csv", function(data, error) {
dataset = data;
alert(dataset.length);
//alert(error);
for(var x=0;x<dataset.length;x++)
{
if (x==0)
{
repository = dataset[0].repository;
}
if (dataset[x].repository!= repository)
{
if ((x > 0 ) || (x==dataset.length))
{
index = 1;
ConsData["name"] = repository;
ConsData["region"] = sbu;
ConsData["checkins"] = checkinsarray;
ConsData["teamsize"] = teamsizearray;
ConsData["Checkintimes"] = checkintimesarray;
tempData=ConsData;
jQuery.extend(MergeData, tempData);
teamsizearray = [];
checkinsarray = [];
checkintimesarray = [];
repository = dataset[x].repository;
sbu = dataset[x].BusinessUnit
checkinsarray.push([index, dataset[x].AvgCheckinCount]);
teamsizearray.push([index, dataset[x].TeamSize]);
checkintimesarray.push([index, dataset[x].MeanBuildTimeHrs]);
}
}
else
{
if (x ==0)
{
index=1;
}
else
{
index=index+1;
}
repository = dataset[x].repository;
sbu = dataset[x].BusinessUnit
checkinsarray.push([index, dataset[x].AvgCheckinCount]);
teamsizearray.push([index, dataset[x].TeamSize]);
checkintimesarray.push([index, dataset[x].MeanBuildTimeHrs]);
}
}
console.log(JSON.stringify(MergeData));
});
Following is the the csv data.
aaa_aaaurf,1,2013,0,0,0,Financial&Risk
aaa_aaaurf,2,2013,0,0,0,Financial&Risk
aaa_aaaurf,3,2013,0,0,0,Financial&Risk
cCG_tzz,1,2013,5,3,100,Financial&Risk
cCG_tzz,2,2013,8,5,80,Financial&Risk
aCG_txz,1,2013,12,3,70,Financial&Risk
GCG_txz,1,2013,21,3,50,Financial&Risk
GCG_txz,2,2013,12,3,70,Financial&Risk

Can you use lodash?
var names = {
'characters': [
{ 'name': 'barney' },
{ 'name': 'fred' }
]
};
var ages = {
'characters': [
{ 'age': 36 },
{ 'age': 40 }
]
};
_.merge(names, ages);
// → { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
var food = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var otherFood = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(food, otherFood, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }

Related

Object destructuring in a loop

How can I achieve this without hardcoding the index?
const { TargetQuantity: targetQuantity1 } = res.data.d.results[0]
const { TargetQuantity: targetQuantity2 } = res.data.d.results[1]
const { TargetQuantity: targetQuantity3 } = res.data.d.results[2]
const { TargetQuantity: targetQuantity4 } = res.data.d.results[3]
try this:
const results = [
{ TargetQuantity: 1 },
{ TargetQuantity: 2 },
{ TargetQuantity: 3 },
{ TargetQuantity: 4 }
];
results.map((item, i) => {
let str ="TargetQuantity"+ (i+1) +" = item.TargetQuantity";
eval(str)
});
This will create global variables TargetQuantity1,TargetQuantity2, TargetQuantity3 ... and so on
const results = [
{TargetQuantity: 1},
{TargetQuantity: 2},
{TargetQuantity: 3},
{TargetQuantity: 4}
];
(function (context){
for(let i = 0; i < results.length; i++){
context[`targetQuantity${i+1}`] = results[i].TargetQuantity;
}
})(this);
console.log(targetQuantity3);
But why would you wanna do that?

populating a deep key/value in javascript object with dynamic non-hard-coded path

I have
let mydata = {
section_a: {
color: "red",
shape: "cube"
},
section_b: {
length: 34
}
}
Now I want to write a function that'll insert a new key/value at a path that is dynamic and can change from call to call.
let path = "section_b.go.real.deep";
let newKey = "age";
let newVal = 50;
so that mydata becomes:
{
section_a: {
color: "red",
shape: "cube"
},
section_b: {
length: 34,
go: {
real: {
deep: {
age: 50
}
}
}
}
}
Is there any technique to allow something like that? creation of a deep element, along with any potential dynamic hierarchy?
Here's a one-liner:
let mydata = {
section_a: {
color: "red",
shape: "cube"
},
section_b: {
length: 34
}
};
let path = "section_b.go.real.deep";
let newKey = "age";
let newVal = 50;
path.split(".").reduce((obj,key) => obj[key] || (obj[key] = {}), mydata)[newKey] = newVal;
console.log(mydata);
Maybe you're looking for something like this:
let mydata = {
section_a: {
color: "red",
shape: "cube"
},
section_b: {
length: 34
}
};
let path = "section_b.go.real.deep";
let newKey = "age";
let newVal = 50;
var items = path.split(".");
var item = mydata;
for (var prop of items) {
if (!item[prop]) {
item[prop] = {};
}
item = item[prop];
};
item[newKey] = newVal;
console.log(mydata);

Cant access data inside nested array of objects

I have an array of objects that I want to iterate over and create a new array of objects.
First I map over the data, then I loop through each object to extract the values. I want to store the Location name and value from each object.
My code is returning null results. I can't change the way data is declared. Can someone help me understand why I keep getting null results?
[
{
"euValue": null,
"asValue": null
}
]
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
let euValue, asValue;
formattedData = data.map(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
euValue = _this.Location === "Europe" ? _this.Value : null;
asValue = _this.Location === "Asia" ? _this.Value : null;
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
Edit
Expected result is
[
{
"euValue": “Ireland”,
"asValue": “China”
}
]
Assuming that inside data you could have multiple objects with a Location array that have only 2 objects (one for Europe and another one for Asia) you should change your function to something like this
const data = [
{
Locations: [
{
Location: { Name: "Europe" },
Value: "Ireland"
},
{
Location: { Name: "Asia" },
Value: "China"
}
]
}
];
const formatData = () => {
// iterate all data objects
return data.map((topLocation) => {
const res = {};
// loop over Location children objects
topLocation.Locations.forEach((location) => {
const { Name } = location.Location;
// decide where to save Value base on the Location.name
if (Name === "Europe") {
res.euValue = location.Value;
} else if (Name === "Asia") {
res.asValue = location.Value;
}
});
return res;
});
};
const newData = formatData();
console.log(newData);
you missing a second loop also you overwriting the usValue and euValue and you better use forEach instead of map in this case.
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = (data) => {
let formattedData = [],
values = {};
data.forEach(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
_this.forEach(el => {
if (el.Location.Name === "Europe") {
values["euValue"] = el.Value || null
}
if (el.Location.Name === "Asia") {
values["asValue"] = el.Value || null
}
})
}
}
});
formattedData.push(values)
return formattedData;
};
console.log(formatData(data))
I don't know what do you want to get from your code but this code may help you.
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
formattedData = data.map(location => {
let euValue = [],
asValue = [];
for (const l in location.Locations) {
if (location.Locations.hasOwnProperty(l)) {
const _this = location.Locations[l];
if (_this.Location.Name === "Europe")
euValue.push(_this.Value);
else if (_this.Location.Name === "Asia")
asValue.push(_this.Value);
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
I'm sure many of the other answers are fine but the way I did it was to do the classic for loop to iterate over the data. I would have liked to have kept your ternary operators but I think you may need the if/else syntax.
var data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
let euValue, asValue;
formattedData = data.map(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
for (let i = 0; i < _this.length; i++) {
if (_this[i].Location.Name === "Europe") {
euValue = _this[i].Value;
} else if (_this[i].Location.Name === "Asia") {
asValue = _this[i].Value;
} else {
euValue, asValue = null;
}
}
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
Using Array.prototype.flatMap() might help you get the array you desire in a cleaner way:
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
const formattedData = data.flatMap(item => {
const object = {}
item.Locations.map(location => {
const continent = location.Location.Name
let country = {}
if (continent === 'Europe') country = {
euValue: location.Value
}
if (continent === 'Asia') country = {
asValue: location.Value
}
Object.assign(object, country)
});
return object
});
return formattedData;
}
const newData = formatData();
console.log(newData);

Can I set a variable to be a multipart property of an object?

I want to be able to set an object property with a variable in a way that lets me make the variable multipart sometimes and single part other times. The code below doesn't work but I think it illustrates what I'm trying to accomplish.
var mekBldr = {
mecha: {
rightLimbs: {
legs: {
rightleg01: {
cost: 0,
classification: ''
}
}
},
leftLimbs: {
legs: {
leftleg01: {
cost: 0,
classification: ''
}
}
}
}
};
var part1 = 'leftLimbs';
var part2 = 'legs';
var multi = part1[part2];
// the goal: mekBldr.mecha.leftLimbs.legs.leftleg01.cost = 5;
mekBldr.mecha[multi].leftleg01.cost = 5;
How about this.
Object.prototype.select = function(route) {
var newObj = this;
route.forEach(function(key) {
newObj = newObj[key];
});
return newObj;
};
You can use the above method like so.
var mekBldr = {
mecha: {
rightLimbs: {
legs: {
rightleg01: {
cost: 0,
classification: ''
}
}
},
leftLimbs: {
legs: {
leftleg01: {
cost: 0,
classification: ''
}
}
}
}
};
var part1 = 'leftLimbs';
var part2 = 'legs';
var multi = [part1, part2];
mekBldr.mecha.select(multi).leftleg01.cost = 5;

Get duplicate key names json jquery

I want an array which will fetch me duplicate keys of the json
Ex:
var catalog=[
{ ip: 'ipId_1', name: '192.160.121.11' },
{ ip: 'ipId_dyn_1_0', name: '192.160.121.12' },
{ ip: 'ipId_dyn_1_1', name: '192.160.121.12' }
];
Since 192.160.121.12 is repeating, i want an array like [ipId_dyn_1_0, ipId_dyn_1_1],
Tried so far (Fiddle Demo):
var categories =[];
var dup= [];
$.each(catalog, function(index, value) {
console.log( categories+''+value.name);
if ($.inArray(value.name, categories) == -1) {
categories.push(value.name);
}else{
dup.push(value.ip);
console.log(value.ip);
}
});
console.log(categories);
console.log(dup);
var cat_inverted = {}, categories = [];
$.each(catalog, function(index, value) {
if (cat_inverted[value.name]) {
cat_inverted[value.name].push(value.ip);
} else {
cat_inverted[value.name] = [value.ip];
categories.push(value.name);
}
});
var dup = [];
for (var name in cat_inverted) {
if (cat_inverted[name].length > 1) {
$.each(cat_inverted[name], function(i, ip) {
dup.push(ip);
});
}
}
Check:
var catalog=[
{ ip: 'ipId_1', name: '192.160.121.11' },
{ ip: 'ipId_dyn_1_0', name: '192.160.121.12' },
{ ip: 'ipId_dyn_1_1', name: '192.160.121.12' }
];
var my = {};
var dup = [];
$.each(catalog, function(index, value) {
if(!!!my[value.name]) {
my[value.name] = [];
}
my[value.name].push(value.ip);
});
$.each(my, function(index, value) {
if(value.length > 1) {
$.each(my[index], function(i, val) {
dup.push(val);
});
}
});
console.log(dup);
jsfiddle
If you use this:
var catalog=[
{ ip: 'ipId_1', name: '192.160.121.11' },
{ ip: 'ipId_dyn_1_0', name: '192.160.121.12' },
{ ip: 'ipId_dyn_1_1', name: '192.160.121.12' }
];
var values = {};
$.each(catalog, function(index, data) {
var name = data.name;
if(typeof values[name] == 'undefined') values[name] = [];
values[name].push(data.ip);
});
var dupes = [];
$.each(values,function(name,indexes) {
if(indexes.length > 1)
{
dupes.push(indexes);
}
});
console.dir(dupes);
dupes will now contain an array of arrays (sets of duplicates)
Give it a run and see how it works for ya
I would use lodash.js or underscore.js for this task because of the functional approach. You are more flexible in changing your task when using this approach.
You can store your data in an variable and later easily transform them to your desired data structure.
var catalog=[
{ ip: 'ipId_1', name: '192.160.121.11' },
{ ip: 'ipId_dyn_1_0', name: '192.160.121.12' },
{ ip: 'ipId_dyn_1_1', name: '192.160.121.12' }
];
var categoriesObjectsUniqe =[];
var categories =[];
var dupObjects= [];
var dup= [];
categoriesObjectsUniqe = _.unique(catalog, 'name');
categories = _.map(categoriesObjectsUniqe, function(val) {
return val.name; })
dupObjects = _.filter(catalog, function(current) {
return arr = _.filter(catalog, function(currentInner) {
return currentInner.name === current.name; }).length > 1;
});
dup = _.map(categoriesObjUniqe, function(val) {
return val.ip; })
console.log('uniqe Objects :');
console.log(categoriesObjectsUniqe);
console.log('uniqe IPs :');
console.log(categories);
console.log('duplicate Objects :');
console.log(dupObjects);
console.log('duplicate ips :');
console.log(dup);
Here is the fiddle for that.
http://jsfiddle.net/3wHfB/94/

Categories