How to merge an array of objects by key? - javascript

I have this object:
[{
"NOMOR_CB": "CB/20-0718",
"ITEM": "ABC"
}, {
"NOMOR_CB": "CB/20-0719",
"ITEM": "A1"
}, {
"NOMOR_CB": "CB/20-0719",
"ITEM": "A2"
}]
I'd to merge the values of the same NOMOR_CB so the values of the same NOMOR_CB is combined. This is the desired output.
[{
"NOMOR_CB": "CB/20-0718",
"ITEM": "ABC"
}, {
"NOMOR_CB": "CB/20-0719",
"ITEM": "A1, A2"
}]
How do I loop over the object to have the desired output?
My current loop (unable to combine the values):
var arr_test = "[";
$.each(response.arr_json, function(i, data) {
arr_test += '{"NOMOR_CB":"'+ data.NOMOR_CB +'",';
arr_test += '"ITEM":"'+ data.ITEM +'"},';
})
var test = arr_test.replace(/,\s*$/, "");
test += "]";
document.write(test);

You can use .reduce() to summarise your array into an object. Use Object.entries to convert the object into an array. You can map to form the desired object format.
let arr = [{"NOMOR_CB":"CB/20-0718","ITEM":"ABC"},{"NOMOR_CB":"CB/20-0719","ITEM":"A1"},{"NOMOR_CB":"CB/20-0719","ITEM":"A2"}];
let result = Object.entries(arr.reduce((c, {NOMOR_CB,ITEM}) => {
c[NOMOR_CB] = c[NOMOR_CB] || [];
c[NOMOR_CB].push(ITEM);
return c;
}, {})).map(([i, a]) => Object.assign({}, {NOMOR_CB: i,ITEM: a.join(', ')}));
let str = JSON.stringify(result); //Optional. Based on your code, you are trying to make a string.
console.log(str);
And dont concatenate strings to form a json. You can use JSON.stringify(result); to convert js object to string.
Doc: .reduce(), .map()

Related

how to get only one value from array data and convert it into comma separted values. using javascript without template literals

i have array data in the format given below
const data= [
{
name: "productname",
id: "1356",
price: "0.00",
category: "Health",
position: "1",
list: "New Products",
stocklevel: "20",
brand: "Health"
},
{
name: "productname2",
id: "5263",
price: "0",
category: "Hair",
position: "2",
list: "New Products",
stocklevel: "",
brand: "Hair"
}]
from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-
product1name: "productname",
product2name: "productname2",
...
i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried
var dataByComa = '';
var Values = data
.map(function (p, i) {
return Object.keys(data[i]).map(function (k) {
return "prod" +" " + ": " + JSON.stringify(data[i][k]);
});
}).map(function (v) {
return v.join(",\n"); });
var commaValues = Values.join(",\n");
return commaValues;
with this code i can able to convert array data into comma separated values but i want only productnames.
Note :- Without using template template literals.
Edit: I'm more clear on what the OP was looking for now - here is an answer that fulfills all the requirements
let commaValues = ""
for (let i = 0; i < data.length; i++) {
commaValues += ("product" + (i + 1) + "name: " + "\"" + data[i]["name"] + "\", ")
}
// result: 'product1name: "productname", product2name: "productname2", '
You can do that using reduce. It takes a function as first and an initial value as second parameter (here an empty object {}).
The variable "previous" keeps track of the current state of the (initially empty) new object while the function adds the name of every single Element from the "data" array to the object.
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
EDIT:
As i realized, you actually want a string as result. In that case you could do:
var result = data.reduce((previous, element) => {
previous[element.name] = element.name;
return previous;
}, {})
var csvWithBrackets = JSON.stringify(result)
var csv = csvWithBrackets.substring(1, csvWithBrackets.length-1)
However the answer from Pzutils seems more compact.
You can iterate through the data and assign the value to an external variable like this:
let finalData = {}
data.forEach((item, index) => {
finalData[`product${index+1}name`] = item.name
})

Add nested json object item to another json item

I want to add two nested objects in JSON in typescript.
In JSON given below I want to add second JSON's activityLogs item in first JSON's activityLogs.
JSON1:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
JSON2:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}]
Result:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"},
{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
How I can do this?
You can use push() with the spread operator or concat and reassign:
var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
JSON1[0].activityLogs.push(...JSON2[0].activityLogs)
console.log(JSON1)
This assumes that your json arrays contain just the one top-level object. If that's not the case you need to add more details about how the two arrays are synchronized (for example will vehicleno be the same in both?).
As an example, if the vehicleno is a unique identifier in both arrays you could create a lookup of the JSON1 values and the use that to push into the appropriate arrays. This will update JSON1 in place even if it contains multiple vehicles:
var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
let lookup = JSON1.reduce((lookup, obj) => {
lookup[obj.vehicleno] = obj
return lookup
}, {})
JSON2.forEach(obj => lookup[obj.vehicleno].activityLogs.push(...obj.activityLogs))
console.log(JSON1)
You can use concatination array method.
let json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}];
let json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]
let result = json1[0].activityLogs.concat(json2[0].activityLogs);
console.log(result);
The simplest way is to concat the activityLogs:
var arr1 = [{
"vehicleno": "SV028",
"devicE_CODE": "8505",
"activityLogs": [{
"gpsdate": "01/03/2019",
"gpstime": "13:40:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:38:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:37:18"
}
]
}];
var arr2 = [{
"vehicleno": "SV028",
"devicE_CODE": "8505",
"activityLogs": [{
"gpsdate": "01/03/2019",
"gpstime": "13:46:18"
},
{
"gpsdate": "01/03/2019",
"gpstime": "13:43:18"
}
]
}];
var arr3 = arr1[0].activityLogs.concat(arr2[0].activityLogs);
console.log(arr3);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
Note this will only work if you only have one object in the top-level array.
result = json1;
/// result = Object.assign({}, json1); if you don't want to mutate the original json1
result.forEach(elem1 => elem1.activityLogs
.concat(json2.find(elem2 => elem2.vehicleno === elem1.vehicleno).activityLogs));
Concat the activityLogs of the second array item to the first array item by finding the matching element by vehicleno..
var json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
},{"vehicleno":"SV02","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
{"gpsdate":"01/03/2019","gpstime":"13:38:18"},
{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]
var json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}];
var jsonCont = json1.concat(json2);
var result = Object.values(jsonCont.reduce((acc, o)=>{
if(!acc.hasOwnProperty(o['vehicleno'])) {
acc[o['vehicleno']] = Object.assign({}, o);
} else {
acc[o['vehicleno']]['activityLogs'] = acc[o['vehicleno']]['activityLogs'].concat(o['activityLogs']);
}
return acc;
}, {}));
console.log(result);

formatting dynamic json array

I have an json array as follows:
Maindata=[
{"name":"string1"},
{"name":"string2"},
{"name":"string3"}
];
what I need is an array of following type:
data=[
{
"name":"string1",
"name":"string2",
"name":"string3"
}
];
can anybody help me with some methods to obtain required json from original array.
(note: maindata is json array formed dynamically thats why its structure is like that)
Thanks in advance
You could use Object.assign and spread the array elements.
var array = [{ name1: "string1" }, { name2: "string2" }, { name3: "string3" }],
object = Object.assign({}, ...array);
console.log(object);
With reduce, you can do like following
var Maindata = [{
"name1": "string"
}, {
"name2": "string"
}, {
"name3": "string"
}];
var finalObj = Maindata.reduce((acc, cur) => {
Object.assign(acc, cur);
return acc;
}, {})
console.log(finalObj);
You can use Array.forEach or Array.reduce to iterate though the items of the Maindata object and for each item you can iterate through its keys(using Object.keys) and group the data into a new structure.(See the below snippet)
Solution using Array.forEach
var Maindata=[
{"name1":"string1"},
{"name2":"string2"},
{"name3":"string3"}
];
var result = {};
var newMaindata=[];
Maindata.forEach(function(el){
Object.keys(el).forEach(function(key){
result[key]=el[key];
});
});
newMaindata.push(result);
console.log(newMaindata);
Solution using Array.reduce
var Maindata = [{
"name1": "string1"
}, {
"name2": "string2"
}, {
"name3": "string3"
}];
var result ;
var newMaindata = [];
result = Maindata.reduce(function(acc,el) {
Object.keys(el).forEach(function(key) {
acc[key] = el[key];
});
return acc;
},{});
newMaindata.push(result);
console.log(newMaindata);

array map, map array as a key of an array

I know the title might sounds confusing, but i'm stuck for an hour using $.each. Basically I have 2 arrays
[{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
and [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
How do I put one into another as a new property key like
[{
"section_name": "abc",
"id": 1,
"new_property_name": [{
"toy": "car"
}, {
"tool": "knife"
}]
}, {
"section_name": "xyz",
"id": 2,
"new_property_name": [{
"weapon": "cutter"
}]
}]
ES6 Solution :
const arr = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
const arr2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
const res = arr.map((section,index) => {
section.new_property_name = arr2.filter(item => item.id === section.id);
return section;
});
EDIT : Like georg mentionned in the comments, the solution above is actually mutating arr, it modifies the original arr (if you log the arr after mapping it, you will see it has changed, mutated the arr and have the new_property_name). It makes the .map() useless, a simple forEach() is indeed more appropriate and save one line.
arr.forEach(section => {
section.new_property_name = arr2.filter(item => item.id === section.id));
});
try this
var data1 = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var data2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
var map = {};
//first iterate data1 the create a map of all the objects by its ids
data1.forEach( function( obj ){ map[ obj.id ] = obj });
//Iterate data2 and populate the new_property_name of all the ids
data2.forEach( function(obj){
var id = obj.id;
map[ id ].new_property_name = map[ id ].new_property_name || [];
delete obj.id;
map[ id ].new_property_name.push( obj );
});
//just get only the values from the map
var output = Object.keys(map).map(function(key){ return map[ key ] });
console.log(output);
You could use ah hash table for look up and build a new object for inserting into the new_property_name array.
var array1 = [{ "section_name": "abc", "id": 1 }, { "section_name": "xyz", "id": 2 }],
array2 = [{ "toy": "car", "section_id": 1 }, { "tool": "knife", "section_id": 1 }, { "weapons": "cutter", "section_id": 2 }],
hash = Object.create(null);
array1.forEach(function (a) {
a.new_property_name = [];
hash[a.id] = a;
});
array2.forEach(function (a) {
hash[a.section_id].new_property_name.push(Object.keys(a).reduce(function (r, k) {
if (k !== 'section_id') {
r[k] = a[k];
}
return r;
}, {}));
});
console.log(array1);
Seems like by using Jquery $.merge() Function you can achieve what you need. Then we have concat function too which can be used to merge one array with another.
Use Object.assign()
In your case you can do it like Object.assign(array1[0], array2[0]).
It's very good for combining objects, so in your case you just need to combine your objects within the array.
Example of code:
var objA = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var objB = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var objC = Object.assign({},objA[0],objB[0]);
console.log(JSON.stringify(objC));// {"section_name":"abc","id":1,"toy":"car","section_id":1}
For more info, you can refer here: Object.assign()
var firstArray = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}],
secondArray = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var hash = Object.create(null);
firstArray.forEach(s => {
hash[s.id] = s;
s['new_property_name'] = [];
});
secondArray.forEach(i => hash[i['section_id']]['new_property_name'].push(i));
console.log(firstArray);

Finding an array's objects that are not present in another array by property

I'm looking for a way to find any objects in one array that are not present in another array based upon that object's property. What's the best way to do this with jQuery or underscore?
Given the following example:
"array1":[
{"testProperty":"A"},
{"testProperty":"B"},
{"testProperty":"C"}
]
"array2":[
{"testProperty":"A", "User":"Smith"},
{"testProperty":"B", "User":"Smith"},
]
I would want to return the third object from array1 whose testProperty is "C" since it's not present in array2.
I was able to find several examples of this issue here on stackoverflow, but not when needing to do so using properties from those objects.
I'm not sure if this counts, but if you can use lodash instead of underscore, there is a nice function called differenceBy:
var _ = require("lodash");
var array1 = [
{"testProperty":"A"},
{"testProperty":"B"},
{"testProperty":"C"}
]
var array2 = [
{"testProperty":"A", "User":"Smith"},
{"testProperty":"B", "User":"Smith"}
]
var result = _.differenceBy(array1, array2, function(item) {
return item["testProperty"]
});
console.log(result);
A proposal in plain Javascript with a hash table for look-up.
var data = { "array1": [{ "testProperty": "A" }, { "testProperty": "B" }, { "testProperty": "C" }], "array2": [{ "testProperty": "A", "User": "Smith" }, { "testProperty": "B", "User": "Smith" }, ] },
result = data.array1.filter(function (a) {
return !this[a.testProperty];
}, data.array2.reduce(function (r, a) {
r[a.testProperty] = true;
return r;
}, Object.create(null)));
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
You can use filter with map
var a = {'array1': [{"testProperty":"A"}, {"testProperty":"B"}, {"testProperty":"C"}], 'array2': [{"testProperty":"A", "User":"Smith"}, {"testProperty":"B", "User":"Smith"}]};
var result = a.array1.filter(function(e) {
return a.array2.map(el => { return el.testProperty}).indexOf(e.testProperty) == -1;
});
console.log(result);
here's a version in plain es6 js using filter and some method:
array1 = [
{"testProperty":"A"},
{"testProperty":"B"},
{"testProperty":"C"}
];
array2 =[
{"testProperty":"A", "User":"Smith"},
{"testProperty":"B", "User":"Smith"},
]
var r = array1.filter(x =>
! Object.keys(x).some(z =>
array2.some(w =>
Object.keys(w).some(y => y === z && w[y] === x[z])
)));
document.write(JSON.stringify(r))
You could use underscore's reject and some to get what you want:
var result = _.reject(array1, item => _.some(array2, {testProperty: item.testProperty}));
If performance is a concern and testProperty is an unique key of the objects in array2 then you could create a hash using indexBy and check for the result using has:
var hash = _.indexBy(array2, 'testProperty');
var result = _.reject(array1, item => _.has(hash, item.testProperty));

Categories