Populate parent Object by comparing parent Array - javascript

Am having an arrray of Objects which again contains the id's of the parent Object:
eg:-
$scope.result=[
{
"id": 1,
"name": ABC,
"type": PQR,
"parentId": 2
},
{
"id": 2,
"name": ABC,
"type": PQR,
"parentId": 1
}]
I would like to convert this JSON in to the following wherin I will be having the parentObject in place of parentId's
$scope.result=[
{
"id": 1,
"name": ABC,
"type": a,
"parentId": {
"id": 2,
"name": PQR,
"type": b,
"parentId": 1
}
},
{
"id": 2,
"name": PQR,
"type": b,
"parentId": {
"id": 1,
"name": ABC,
"type": a
}
}
]
Can anybody help me with this conversion..

Assuming parentId will reference to one element
angular.forEach($scope.result, function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});
Since your tags doesn't contain angularjs, I'm using Array.prototype.forEach here
$scope.result.forEach(function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});

Will do 2 loops first one to fill a hash with keys of the ids, second will loop to replace parent id with actual object:
$scope = {}
$scope.result=[
{
"id": 1,
"name": "ABC",
"type": "PQR",
"parentId": 2
},
{
"id": 2,
"name": "ABC",
"type": "PQR",
"parentId": 1
}]
parents = {}
for(i=0;i<$scope.result.length;i++){
parents[$scope.result[i]["id"]] = jQuery.extend({}, $scope.result[i]); // Clone object
}
for(i=0;i<$scope.result.length;i++){
$scope.result[i]["parentId"] = parents[$scope.result[i]["parentId"]]
}
$scope.result

Related

JavaScript: filter array of objects by another

I'm trying to filter some objects based on another array of objects. So I'm getting data from an API. These are for example receipts:
[
{
"id": 1,
"name": "test",
"category": {
"id": 1,
"name": "Cookies",
},
},
{
"id": 2,
"name": "test2",
"category": {
"id": 2,
"name": "Candy",
},
}
]
Then I'm trying to filter the objects on the category name based on another array of categories.
I've created a function for this:
function onSelectCategory(category) {
let receiptsList = receipts.filter((a) =>
a.category.includes(category.name)
);
setReceiptsView(receiptsList);
setSelectedCategory(category);
}
const category = [ { "id": 2, "name": "Candy" } ];
onSelectCategory(category);
When I run this function, I get an empty Array []. I can't really figure out what I'm doing wrong.
Since the param seems to be an array of objects, you need to use Array#some for comparison instead:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const receiptsList = receipts.filter(({ category }) =>
categories.some(({ name }) => name === category.name)
);
console.log(receiptsList);
Another solution using Set:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const categorySet = new Set(categories.map(({ name }) => name));
const receiptsList = receipts.filter(({ category }) =>
categorySet.has(category.name)
);
console.log(receiptsList);
Assuming that category (the parameter) is a string, the issue is that you are attempting to get the attribute name from the string, when you should be comparing the string to the object.
Try this:
a.category.name == category;
instead of
a.category.includes(category.name)
I may be wrong aboout assuming that category is a string, please clarify by telling us what the parameter category is equal to.

Copy second nested array of objects into first nested array of objects

How can I assign key value from array of object to another array object
I would like to assign the key:value pair to the existing array of object from the another array of objects.
I have check this thread but it is not working in my case.
I have tried something like this but that is not returning the desired output that I am looking for.
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
let result;
var A1 = DataA.options.map((v) => {
console.log(v);
result = v;
})
var A2 = DataB.options.map(v => {
result.options = v;
console.log("result",result);
})
let arr3 = DataA.options.map((item, i) => Object.assign({}, item, DataB[i]));
console.log(arr3);
Result will be I need as below:
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A", "value": 10 },
{ "id": 2, "name": "Type B", "value": 20 },
{ "id": 3, "name": "Type C", "value": 30 }]
}
I need to merge the deep clone of the array that is slightly different from this thread.
The linked duplicate does actually address your question, but you need to adjust it to your situation and not just copy paste.
DataA.options = DataA.options.map((item, i) => Object.assign({}, item, DataB.options[i]));
but since this mutates the original DataA object anyway, you may as well just use forEach() and avoid creating the intermediate array from .map().
DataA.options.forEach((item, i) => Object.assign(item, DataB.options[i]));
Both of the above assume that the options arrays of both objects are a. of the same length, and b. sorted by id. To avoid these assumptions you can use .find() to look for matching elements instead of relying on index.
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
const DataA = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
console.log(DataA)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter a complex object based on another complex object property

So there is an complex Object A
{
"AId": 34,
"children": [
{
"id": 1,
"name": "name1",
"prop": "Hello"
},
{
"id": 2,
"name": "name2",
"prop": "world"
}
]
}
and there is complex Object B
[
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
]
I want to remove all elements in object B which are in Object A children just based on id. So A object children have id 1 & 2 in example which are also in object B so those id 1 & 2 needs to be removed in object B,what is the best way to do this? hopefully i explained this well
try with foreach
oB= [
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
]
oA={
"AId": 34,
"children": [
{
"id": 1,
"name": "name1",
"prop": "Hello"
},
{
"id": 2,
"name": "name2",
"prop": "world"
}
]
}
oA.children.forEach(x=>{
oB.forEach(y=>{
if(x.id==y.id) oB.shift()
})
})
console.log(oB)
A.children.forEach(x=>{
this.B.forEach(y=>{
if(x.id==y.id)
{
this.A.children = this.A.children.filter(s => s.id !== x.id);
}
})
});

Convert array of object values from int to string

I have the following array
[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }
How can I convert that to
[ { "id": '1', "name": "Test" }, { "id": '2', "name": "Test2" }
For all the objects in an array, you want to convert a property type from number to string. You can use Array.forEach to achieve the same.
let arr = [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }];
arr.forEach(v => v.id += '');
console.log(arr);

Javascript create 2 arrays from object data

I have some data and I need a loop which creates 2 arrays...
So I first create the 2 arrays:
namelist = [];
countList = [];
{
"id": "622",
"name": "main",
"sub": {
"637": {
"id": "637",
"name": "name 1",
"stats": {
"count": 5
}
},
"638": {
"id": "638",
"name": "name 2",
"stats": {
"count": 10
}
}
}
}
The desired result for this example would be:
For namelist:
['name 1', 'name 2']
For countList:
[5, 10]
How can I do this?
var nameList = [];
var countList = [];
var myObj =
{
"id": "622",
"name": "main",
"sub": {
"637": {
"id": "637",
"name": "name 1",
"stats": {
"count": 5
}
},
"638": {
"id": "638",
"name": "name 2",
"stats": {
"count": 10
}
}
}
};
for(var key in myObj.sub){
nameList.push(myObj.sub[key].name);
countList.push(myObj.sub[key].stats.count);
}
console.log(nameList);
console.log(countList);
for(var key in obj.sub){
nameList.push(obj.sub[key].name);
countList.push(obj.sub[key].stats.count;
}
Object.keys may help you to walk through object properties. Example related to your object:
var namelist = [],
countList = [],
obj = {
"id": "622",
"name": "main",
"sub": {
"637": {
"id": "637",
"name": "name 1",
"stats": {
"count": 5
}
},
"638": {
"id": "638",
"name": "name 2",
"stats": {
"count": 10
}
}
}
};
Object.keys(obj.sub).forEach(function(item) {
namelist.push(obj.sub[item].name);
countList.push(obj.sub[item].stats.count);
});
console.log(namelist, countList);
Working example: https://jsfiddle.net/ry0zqweL/
Obviously, you can optimise it in many ways. It's just illustrating one of the many solutions.

Categories