Combine arrays into objects depending on elements - javascript

I have two arrays, Array 1 containing the sections, and Array 2 containing the objects, the goal is to insert the objects from Array 2 inside the objects into Array1 depending on the type (Sides or Sauces), for example: Each object from Array 2 containing the element type:Sauces should be set in an array inside the object of Array 1 with type:Sauces and so on. I tried by using the forEach function but since I'm relatively new to JavaScript I don't know how to proceed
Array 1 (Sections)
Array [
Object {
"required": false,
"type": "Sides",
},
Object {
"required": true,
"type": "Sauces",
},
]
Array 2 (List of Objects)
Array [
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
this is what I'm trying to achieve:
Array [
Object {
"required": false,
"type": "Sides",
"data": [
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
},
Object {
"required": true,
"type": "Sauces",
"data":[
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
]
},
]

this should work for you:
arr1.forEach((a,i) => {
a["data"] = arr2.filter(b => b.type == a.type);
})

I name Array1 = categories
I name Array2 = elements
You need to map on each.
const test = categories.map((cat) => {
elements.map((el) => {
if (el.type === cat.type) {
cat.elements.push(el);
}
return el;
});
return cat;
});
console.log(test);

Related

How to push object value from first array to second array by id?

I have an 2 array, first array:
[
{
"id": 1,
"name": "jumlah_sd",
"title": "Jumlah SD",
"value": "1222"
},
{
"id": 2,
"name": "jumlah_smp",
"title": "Jumlah SMP",
"value": "1322"
}
]
and second array with no value:
[
{
"id": 1,
"name": "jumlah_sd",
"title": "Jumlah SD"
},
{
"id": 2,
"name": "jumlah_smp",
"title": "Jumlah SMP"
},
{
"id": 3,
"name": "jumlah_sma",
"title": "Jumlah SMA"
}
]
My question is, how to push by their "id" object value in first array to second array in JavaScript? And if there is no value in other object, so the value become "value": "" in second array.
One way to do is to create an object with the id as the key and value as value for easy lookup.
After that map through the second array and add the id using the lookup object.
const arr1 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD", "value": "1222" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP", "value": "1322" }]
let arr2 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP" },{ "id": 3, "name": "jumlah_sma", "title": "Jumlah SMA" }]
const idLookup = arr1.reduce((acc,{id,value}) => {
acc[id]??=value
return acc
},{})
arr2 = arr2.map((x) => ({...x, value: idLookup[x.id]||""}))
console.log(arr2)
Another approach is to use find inside map but it will intuitively be slower since the find is called in each iteration inside the map
const arr1 = [ { "id": 1, "name": "jumlah_sd","title": "Jumlah SD", "value": "1222" }, { "id": 2,"name": "jumlah_smp", "title": "Jumlah SMP", "value": "1322" }]
let arr2 = [ { "id": 1, "name": "jumlah_sd", "title": "Jumlah SD" }, { "id": 2, "name": "jumlah_smp", "title": "Jumlah SMP" }, { "id": 3, "name": "jumlah_sma", "title": "Jumlah SMA" }]
arr2 = arr2.map((x) => {
const entry = arr1.find(({id}) => x.id === id)
return {...x,value:entry?.value||''}
})
console.log(arr2)

Paasing an object into an array of arrays

Have an object that needs to be pass inside the array of source using javascript,throwing an error spec is undefined when using push function. will push function work for this scenario
var a = [
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
}]
var b = {
"data": {
"path": "google/path",
"name": "goldengate",
"Id": "11234vndslknvlsmnv",
},
"ref": "www.xyz.com",
"id": "6452367e5375",
"resourceType": "app"
}
a.spec.sink.source.push(b);
would expect b to be pushed to source
An array with string keys is not a valid structure, you need to convert a to an object
var a = { // <-- here
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [
{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
} // <-- here

Convert nested JSON to flat JSON - In order to insert them as records in SQL

I have a JSON string in nested pattern like below:
NESTED (Just Example):
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
I want an option or way to convert this nested JSON string to a flat JSON string so that I can insert them like a record in SQL table.
Can you please help on how to structure the JSON from nested to flat?

How to return a childobject from json with lodash?

Suppose I have the following json file and I would like to return the 'existing.primaryBundle.products' array preferrably with lodash:
{
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}
]
}
]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [
{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
},
{
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
},
{
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}
]
}
}
}
I have tried lodash and use this statement:
list2 = _.pick(existing,'primaryBundle.products')
But this returns an error and not the wanted result. How can I select this products array?
you could use _.get(nameOfObject, 'existing.primaryBundle.products') of course you would need to name your object like I've done below with sampleObject;
check out the lodash docs too
const sampleObject = {
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
}, {
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}]
}]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
}, {
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
}, {
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}]
}
}
}
console.log(_.get(sampleObject, 'existing.primaryBundle.products'));
The main reason why it returns an error is because existing is not a global scoped object, you have to assign object to some variable like const obj = {...} and then pass the parameter to _pick method as obj.existing, yet I don't see a reason to use lodash in here, you can just reference the path to that object directly.

Nested Loops in angularjs

I have been using nested loops to access data of the json object to display the id and type of topping, however its not working. Here's my code:
var j_obj = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}, {
"id": "1002",
"type": "Chocolate"
}, {
"id": "1003",
"type": "Blueberry"
}, {
"id": "1004",
"type": "Devil's Food"
}]
},
"topping": [{
"id": "5001",
"type": "None"
}, {
"id": "5002",
"type": "Glazed"
}, {
"id": "5005",
"type": "Sugar"
}, {
"id": "5007",
"type": "Powdered Sugar"
}, {
"id": "5006",
"type": "Chocolate with Sprinkles"
}, {
"id": "5003",
"type": "Chocolate"
}, {
"id": "5004",
"type": "Maple"
}]
}
var Outer_log=[];
debugger
angular.forEach(j_obj, function(an_object){
//Outer_log.push("ID : "+an_object.id+" type : "+an_object.type);
angular.forEach(an_object.topping,function(innerobject){
Outer_log.push("ID : "+innerobject.id+" type : "+innerobject.type);
},Outer_log);
});
console.log(Outer_log);
Could someone please highlight the error in above code, Thanks
Without using nested loop you can iterate using angular.forEach like this
var finalArray=[];
angular.forEach(j_obj[0].topping, function(eachobject){
finalArray.push("ID : "+ eachobject.id+" type : "+ eachobject.type);
});
Angulars forEach is intended to iterate over arrays not object. so if you change your code to something like this
var j_obj = [{ ...}] //object is wrapped inside array.
it will work. Another thing is you don't need a nested loop in this case. You can just do:
angular.forEach(j_obj.topping, function(key, value){ ... });
you are iterating over object where as loop run over array.
hope this helps JSfiddle link
var j_obj = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}, {
"id": "1002",
"type": "Chocolate"
}, {
"id": "1003",
"type": "Blueberry"
}, {
"id": "1004",
"type": "Devil's Food"
}]
},
"topping": [{
"id": "5001",
"type": "None"
}, {
"id": "5002",
"type": "Glazed"
}, {
"id": "5005",
"type": "Sugar"
}, {
"id": "5007",
"type": "Powdered Sugar"
}, {
"id": "5006",
"type": "Chocolate with Sprinkles"
}, {
"id": "5003",
"type": "Chocolate"
}, {
"id": "5004",
"type": "Maple"
}]
}]
var Outer_log = [];
angular.forEach(j_obj, function(an_object) {
//Outer_log.push("ID : "+an_object.id+" type : "+an_object.type);
angular.forEach(an_object.topping, function(innerobject) {
Outer_log.push("ID : " + innerobject.id + " type : " + innerobject.type);
}, Outer_log);
});
console.log(Outer_log);

Categories