How can I update this nested object's value if one of its properties match in JS? - javascript

I saw many answers, but I haven't been able to modify any to my need.
Object
{
"id": "476ky1",
"custom_id": null,
"name": "Reunião com o novo Gerente de Vendas - Airton",
"text_content": null,
"description": null,
"status": {
"id": "p3203621_11svBhbO"
},
"archived": false,
"creator": {
"id": 3184709
},
"time_spent": 0,
"custom_fields": [{
"id": "36c0de9a-9243-4259-ba57-bd590ba07fe0",
"name": "Comments",
"value": "dsdsdsds"
}],
"attachments": []
}
Within custom_fields, if the property name's value is Comments, update the value property.
I've tried it like this, using this approach, for example, but it doesn't produce the expected result.
const updatedComment = [{ name: "Comments", value: "The comment is updated"}];
updateNestedObj(taskData, updatedComment)
function updateNestedObj(obj, updates) {
const updateToApply = updates.find(upd => upd.id === obj.id);
if (updateToApply) {
obj.title = updateToApply.content;
obj.note = updateToApply.note;
}
// Apply updates to any child objects
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
updateNestedObj(obj[k], updates);
}
}
}

You're using the wrong property names when you search updates for updateToApply, and then when assigning the value.
When you recurse on children, you need to distinguish between arrays and ordinary objects, so you can loop over the nested arrays. You also have to skip null properties, because typeof null == 'object'.
const updatedComment = [{
name: "Comments",
value: "The comment is updated"
}];
function updateNestedObj(obj, updates) {
let updateToApply = updates.find(upd => upd.name == obj.name);
if (updateToApply) {
obj.value = updateToApply.value;
}
// Apply updates to any child objects
Object.values(obj).forEach(child => {
if (Array.isArray(child)) {
child.forEach(el => updateNestedObj(el, updates));
} else if (typeof(child) === 'object' && child != null) {
updateNestedObj(child, updates);
}
});
}
const taskData = {
"id": "476ky1",
"custom_id": null,
"name": "Reunião com o novo Gerente de Vendas - Airton",
"text_content": null,
"description": null,
"status": {
"id": "p3203621_11svBhbO"
},
"archived": false,
"creator": {
"id": 3184709
},
"time_spent": 0,
"custom_fields": [{
"id": "36c0de9a-9243-4259-ba57-bd590ba07fe0",
"name": "Comments",
"value": "dsdsdsds"
}],
"attachments": []
};
updateNestedObj(taskData, updatedComment)
console.log(taskData);

Try this:
const updatedComment = [{ name: "Comments", value: "A new comment value" }]
// you can add as many updates as you want
function update(obj, updates) {
for (const update in updates) {
for (const field in obj.custom_fields) {
if (obj.obj.custom_fields.name == update.name) {
obj.obj.custom_fields.value = update.value
}
}
}
}
update(obj, updatedComment)

Related

Loop through an array of objects and update parent object count if child object exists

I am using Angular 13 and I have an array of objects like this:
[{
"name": "Operating System",
"checkedCount": 0,
"children": [{
"name": "Linux",
"value": "Redhat",
"checked": true
},
{
"name": "Windows",
"value": "Windows 10"
}
]
},
{
"name": "Software",
"checkedCount": 0,
"children": [{
"name": "Photoshop",
"value": "PS",
"checked": true
},
{
"name": "Dreamweaver",
"value": "DW"
},
{
"name": "Fireworks",
"value": "FW",
"checked": true
}
]
}
]
I would like to loop through the array, check if each object has a children array and it in turn has a checked property which is set to true, then I should update the checkedCount in the parent object. So, result should be like this:
[{
"name": "Operating System",
"checkedCount": 1,
"children": [{
"name": "Linux",
"value": "Redhat",
"checked": true
},
{
"name": "Windows",
"value": "Windows 10"
}
]
},
{
"name": "Software",
"checkedCount": 2,
"children": [{
"name": "Photoshop",
"value": "PS",
"checked": true
},
{
"name": "Dreamweaver",
"value": "DW"
},
{
"name": "Fireworks",
"value": "FW",
"checked": true
}
]
}
]
I tried to do it this way in angular, but this is in-efficient and results in an error saying this.allFilters[i].children[j] may be undefined. So, looking for an efficient manner to do this.
for(let j=0;i<this.allFilters[i].children.length; j++) {
if (Object.keys(this.allFilters[i].children[j]).length > 0) {
if (Object.prototype.hasOwnProperty.call(this.allFilters[i].children[j], 'checked')) {
if(this.allFilters[i].children[j].checked) {
this.allFilters[i].checkedCount++;
}
}
}
}
Use a nested for loop to check all the children. If checked is truthy, increment the count of the parent. You don't need to check if parent.children has any elements since if there are no elements the loop won't run anyways.
// minified data
const data = [{"name":"Operating System","checkedCount":0,"children":[{"name":"Linux","value":"Redhat","checked":!0},{"name":"Windows","value":"Windows 10"}]},{"name":"Software","checkedCount":0,"children":[{"name":"Photoshop","value":"PS","checked":!0},{"name":"Dreamweaver","value":"DW"},{"name":"Fireworks","value":"FW","checked":!0}]}];
for (const parent of data) {
for (const child of parent.children) {
if (child.checked) parent.checkedCount++;
}
}
console.log(data);
No need to complicate it like that, you just need to check checked property in children.
data.forEach((v) => {
v.children.forEach((child) => {
if (child.checked) {
v.checkedCount++;
}
});
});
Using filter + length on children array should do the job:
const data = [{"name":"Operating System","checkedCount":null,"children":[{"name":"Linux","value":"Redhat","checked":true},{"name":"Windows","value":"Windows 10"}]},{"name":"Software","checkedCount":null,"children":[{"name":"Photoshop","value":"PS","checked":true},{"name":"Dreamweaver","value":"DW"},{"name":"Fireworks","value":"FW","checked":true}]}];
data.forEach(itm => {
itm.checkedCount = itm.children?.filter(e => e.checked === true).length ?? 0;
});
console.log(input);
I would suggest going functional.
Using map
const children = arr.map(obj => obj.children);
const result = children.map((child, idx) => {
const checkedCount = child.filter(obj => obj.checked)?.length;
return {
...arr[idx],
checkedCount
};
});
console.log(result)
or using forEach
const result = [];
const children = arr.map(obj => obj.children);
children.forEach((child, idx) => {
const checkedCount = child.filter(obj => obj.checked)?.length;
result[idx] = {
...arr[idx],
checkedCount
};
});
console.log(result)

How to filter and map nested array items while checking whether the to be filtered items meet certain criteria?

I need to filter and map both, array items and each item's child array items while checking whether the to be filtered items have certain properties which meet certain criteria.
What are good array method based approaches for filtering and mapping nested array items?
Required Properties
"productName", "productCategory", "content", "id"
AND also if status inside productImages is not Linked or Existing
Sample Data
[
{
"productName": null,
"productCategory": null,
"productImages": [
{
"content": "1",
"id": null,
"data": null,
"file": null,
"url": null,
"status": "Existing"
},
{
"content": "",
"id": "234",
"data": "test data",
"file": "test file",
"url": null,
"status": "Existing"
}
]
},
{
"productName": null,
"productCategory": "hello category",
"productImages": [
{
"content": "1",
"id": null,
"data": null,
"file": null,
"url": null,
"status": "Existing"
},
{
"content": "",
"id": "234",
"data": "test data",
"file": "test file",
"url": null,
"status": "Existing"
}
]
},
{
"productName": "test product",
"productCategory": "test category",
"productImages": [
{
"content": "1",
"id": "123",
"data": "test data",
"file": "test file",
"url": null,
"status": "Linked"
},
{
"content": "2",
"id": "234",
"data": "test data",
"file": "test file",
"url": "test",
"status": "Linked"
}
]
},
{
"productName": "new product",
"productCategory": "new category",
"productImages": [
{
"content": "2",
"id": "32332",
"data": "test data",
"file": "test file",
"url": "test",
"status": "new"
}
]
}
]
Expected Output
[
{
"productIndex": 3,
"name": "new product",
"category": "new category",
"filteredImages": [
{
"newcontent": "2",
"id": "32332",
},
]
},
]
Code
const filteredProducts = products.filter((element) => element.productName && element.productCategory);
You can do it with one for-of loop:
const incomplete_items = [];
const new_data = []
for (const [index, item] of data.entries()) {
if(item.productName && item.productCategory && item.productImages.every((image) => image.id && image.content && !['Existing', 'Linked'].includes(image.status))){
new_data.push({
productIndex: index,
name: item.productName,
category: item.productCategory,
filteredImages: item.productImages.map((image) => ({ newcontent: image.content, id: image.id, }))
})
} else {
incomplete_items.push(index);
}
}
Working example
const data = [
{
"productName": null,
"productCategory": null,
"productImages": [
{ "content": "1", "id": null, "data": null, "file": null, "url": null, "status": "Existing" },
{ "content": "","id": "234","data": "test data", "file": "test file", "url": null, "status": "Existing" }
]
},
{
"productName": null,
"productCategory": "hello category",
"productImages": [
{ "content": "1", "id": null,"data": null, "file": null, "url": null, "status": "Existing"},
{ "content": "", "id": "234","data": "test data","file": "test file", "url": null, "status": "Existing" }
]
},
{
"productName": "test product",
"productCategory": "test category",
"productImages": [
{ "content": "1", "id": "123", "data": "test data", "file": "test file", "url": null, "status": "Linked" },
{ "content": "2", "id": "234", "data": "test data", "file": "test file", "url": "test","status": "Linked" }
]
},
{
"productName": "new product",
"productCategory": "new category",
"productImages": [
{ "content": "2","id": "32332", "data": "test data", "file": "test file", "url": "test", "status": "new" }
]
}
]
const incomplete_items = [];
const new_data = []
for (const [index, item] of data.entries()) {
if(item.productName && item.productCategory && item.productImages.every((image) => image.id && image.content && !['Existing', 'Linked'].includes(image.status))){
new_data.push({
productIndex: index,
name: item.productName,
category: item.productCategory,
filteredImages: item.productImages.map((image) => ({ newcontent: image.content, id: image.id, }))
})
} else {
incomplete_items.push(index);
}
}
if(incomplete_items.length) console.log(`Items ${incomplete_items} were missing required properties.`);
console.log(new_data);
You can use reduce for this.
Thank you Peter Seliger for pointing me to the double reduce. In terms of readability, do you think it's preferred to use 2 reducers instead of a filter().map() inside the outer reducer?
const sampleData = [{productName:null,productCategory:null,productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:null,productCategory:"hello category",productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:"test product",productCategory:"test category",productImages:[{content:"1",id:"123",data:"test data",file:"test file",url:null,status:"Linked"},{content:"2",id:"234",data:"test data",file:"test file",url:"test",status:"Linked"}]},{productName:"new product",productCategory:"new category",productImages:[{content:"2",id:"32332",data:"test data",file:"test file",url:"test",status:"new"}]}];
const expectedData = sampleData.reduce((acc, val, i) => {
// check if productName and productCategory are available
if (val.productName && val.productCategory) {
// get images that match the criteria and return object in desired format
const filteredImages = val.productImages.reduce(
(matchingImages, { content, id, status }) => {
if (content && id && status !== "Existing" && status !== "Linked") {
matchingImages.push({ newcontent: content, id });
}
return matchingImages;
},
[]
);
// if images are available, all conditions are met
if (filteredImages.length > 0) {
acc.push({
productIndex: i,
name: val.productName,
category: val.productCategory,
filteredImages,
});
}
}
return acc;
}, []);
console.log(expectedData);
.as-console-wrapper { min-height: 100%!important; top: 0; }
A straightforward approach would be based on just two reducer functions, each being properly named according to its implemented purpose, where the outer reduce task iterates the products and the inner task iterates each product's related images.
Thus one achieves both within each reduce task, the filtering and the property mapping for the expected result items.
const input = [{productName:null,productCategory:null,productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:null,productCategory:"hello category",productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:"test product",productCategory:"test category",productImages:[{content:"1",id:"123",data:"test data",file:"test file",url:null,status:"Linked"},{content:"2",id:"234",data:"test data",file:"test file",url:"test",status:"Linked"}]},{productName:"new product",productCategory:"new category",productImages:[{content:"2",id:"32332",data:"test data",file:"test file",url:"test",status:"new"}]}];
function collectNonMatchingImageItem(result, image) {
const { id = null, content = null, status = null } = image;
if (
// loose truthyness comparison ... 1st stage filter (valid image) ...
String(id ?? '').trim() &&
String(content ?? '').trim() &&
String(status ?? '').trim() &&
// ... 2nd stage filter (non matching valid image item) ...
!(/^linked|existing$/i).test(status)
) {
// ... and mapping at once.
result.push({
id,
newcontent: content,
});
}
return result;
}
function collectValidProductWithNonMatchingImages(result, product, idx) {
const {
productName = null,
productCategory = null,
productImages = [],
} = product;
// loose truthyness comparison ... 1st stage filter (valid product) ...
if (
String(productName ?? '').trim() &&
String(productCategory ?? '').trim()
) {
const nonMatchingItems = productImages
.reduce(collectNonMatchingImageItem, []);
// 2nd stage filter (valid product with non matching valid images) ...
if (nonMatchingItems.length >= 1) {
// ... and mapping at once.
result.push({
productIndex: idx,
name: productName,
category: productCategory,
filteredImages: nonMatchingItems,
});
}
}
return result;
}
const result = input
.reduce(collectValidProductWithNonMatchingImages, []);
console.log({ result });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Edit
"... How do you compare the old and new array. I wanted to output a warning if it isn't complete" – Joseph
The above approach shows its flexibility if it comes to the integration of the new requirement ...
const input = [{productName:null,productCategory:null,productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:null,productCategory:"hello category",productImages:[{content:"1",id:null,data:null,file:null,url:null,status:"Existing"},{content:"",id:"234",data:"test data",file:"test file",url:null,status:"Existing"}]},{productName:"test product",productCategory:"test category",productImages:[{content:"1",id:"123",data:"test data",file:"test file",url:null,status:"Linked"},{content:"2",id:"234",data:"test data",file:"test file",url:"test",status:"Linked"}]},{productName:"new product",productCategory:"new category",productImages:[{content:"2",id:"32332",data:"test data",file:"test file",url:"test",status:"new"}]}];
function collectNonMatchingImageItem(collector, image, idx) {
const { id = null, content = null, status = null } = image;
// loose truthyness comparison ... 1st stage filter (valid image) ...
if (
String(id ?? '').trim() &&
String(content ?? '').trim() &&
String(status ?? '').trim()
) {
// ... 2nd stage filter (non matching valid image item) ...
if (
!(/^linked|existing$/i).test(status)
) {
// ... and mapping at once.
collector.result.push({
id,
newcontent: content,
});
collector.nonMatchingAt.push(idx);
}
} else {
collector.invalidAt.push(idx);
}
return collector;
}
function collectValidProductWithNonMatchingImages(collector, product, idx) {
const {
productName = null,
productCategory = null,
productImages = [],
} = product;
// loose truthyness comparison ... 1st stage filter (valid product) ...
if (
String(productName ?? '').trim() &&
String(productCategory ?? '').trim()
) {
const {
result: nonMatchingItems,
nonMatchingAt,
invalidAt,
} = productImages.reduce(
collectNonMatchingImageItem,
{ result: [], nonMatchingAt: [], invalidAt: [] },
);
// report related variables.
let isPlural, itemPhrase, indexPhrase, imageReport;
// 2nd stage filter (valid product with non matching valid images) ...
if (nonMatchingItems.length >= 1) {
// ... and mapping at once.
collector.result.push({
productIndex: idx,
name: productName,
category: productCategory,
filteredImages: nonMatchingItems,
});
// create and collect report item.
isPlural = (nonMatchingAt.length >= 2);
itemPhrase = `item${ isPlural ? 's' : '' }`;
indexPhrase = `${ isPlural ? 'indices' : 'index' }`;
imageReport = `with non matching valid image ${ itemPhrase } at ${ indexPhrase } ${ nonMatchingAt }`;
collector.report.push(
`Valid product item at index ${ idx } ${ imageReport }.`
);
}
if (invalidAt.length >= 1) {
// create and collect report item.
isPlural = (invalidAt.length >= 2);
itemPhrase = `item${ isPlural ? 's' : '' }`;
indexPhrase = `${ isPlural ? 'indices' : 'index' }`;
imageReport = `with invalid image ${ itemPhrase } at ${ indexPhrase } ${ invalidAt }`;
collector.report.push(
`Valid product item at index ${ idx } ${ imageReport }.`
);
}
} else {
// create and collect report item.
collector.report.push(
`Invalid product item at index ${ idx }.`
);
}
return collector;
}
const {
result,
report,
} = input.reduce(
collectValidProductWithNonMatchingImages,
{ result: [], report: [] },
);
console.log({ result, report });
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to parse FractalTransformer with normalizr

I'm trying to use paularmstrong/normalizr on JSON that comes from FractalTransformer and whose nested childs have "data" attribute. Example of JSON:
{
"data": {
"object": "Offer",
"id": "5g6aqocew4qjzl40",
"real_id": 26,
"name": "Random Name",
"created_at": {
"date": "2019-06-18 11:13:08.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"readable_created_at": "1 year ago",
"site": {
"data": {
"object": "Site",
"id": "65zody8vj29vlegd",
"name": "Test Site",
"real_id": 1
}
},
"countries": {
"data": [
{
"object": "Country",
"code": "US",
"name": "United States"
},
{
"object": "Country",
"code": "DE",
"name": "Germany"
}
]
}
},
"meta": {
"include": [
"site",
"countries"
],
"custom": []
}
}
Schemas I use:
export const offerSchema = new schema.Entity('offers')
export const siteSchema = new schema.Entity('sites', {}, {
processStrategy: (value) => {
return { ...value.data }
},
idAttribute: (value) => {
return value.data.id
},
})
export const countrySchema = new schema.Entity('countries')
offerSchema.define({
site: siteSchema,
countries: [countrySchema],
})
Now the issue is that I remove 'data' from the site since it's just one object successfully, but I can't do it in the country case. Whatever I tried with custom processStrategy fails, as country is object that has data which is array (I assume this is where the issue is, going from Entity to Array). And in idAttribute function I always get complete array so can't determine the ID of single entry. So the end result is that the ID of countries is undefined. Any ides?
I actually managed with another approach. I added processStrategy on the parent, 'Offer' in this case, so all 'data' parts get stripped before they reach other child schemas.
const normalizrStripDataOptions = {
processStrategy: (value) => {
const ret = { ...value }
Object.keys(ret).forEach((key) => {
if (ret[key] !== null) {
if (ret[key].data && Array.isArray(ret[key].data)) {
ret[key] = [...ret[key].data]
}
if (ret[key].data && typeof ret[key].data === 'object') {
ret[key] = { ...ret[key].data }
}
}
})
return ret
},
}
export const offerSchema = new schema.Entity('offers', {}, normalizrStripDataOptions)
export const siteSchema = new schema.Entity('sites')
export const countrySchema = new schema.Entity('countries')
offerSchema.define({
site: siteSchema,
countries: [countrySchema],
})

Modify javascript object to specific format

let data = {
"rec": [{
"id": "25837",
"contentId": "25838"
},
{
"id": "25839",
"contentId": "25838"
},
{
"id": "25838"
},
{
"id": "25636",
"contentId": "25837"
}, {
"id": "25640",
"contentId": "25839"
}
]
};
I have a javascript object which I have to manipulate to below format.
{
"childern": [{
"id": "25838",
"childern": [{
"id": "25837",
"contentId": "25838",
"childern": [{
"id": "25636",
"contentId": "25837"
}]
},
{
"id": "25839",
"contentId": "25838",
"childern": [{
"id": "25640",
"contentId": "25839"
}]
}
]
}]
}
If any object dont have contentId it should be at parent level. then all the objects having contentId same as parent id should be at its child level and so on.
I have created a fiddle here but logic is not completed. Any idea or reference to achieve this.
You could create recursive function with reduce method to get the desired result.
let data = {"rec":[{"id":"25837","contentId":"25838"},{"id":"25839","contentId":"25838"},{"id":"25838"},{"id":"25636","contentId":"25837"},{"id":"25640","contentId":"25839"}]}
function nest(data, pid) {
return data.reduce((r, e) => {
if (pid == e.contentId) {
const obj = { ...e }
const children = nest(data, e.id);
if (children.length) obj.children = children
r.push(obj)
}
return r;
}, [])
}
const result = nest(data.rec);
console.log(result[0])

How to append object-key value form one array to other array?

I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:
Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"
If a object is removed or added in the New array, it have to do the same to the Current array.
As far I can see now, I can use some es6 functions :) like:
object-assign, but how to set the new key "fan_count_new"?
How to loop through the array to compare and add or remove + copy the fan_count?
Current array:
[{
"fan_count": 1234,
"id": "1234567890",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
},
{
"fan_count": 4321,
"id": "09876543210",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
}, ...
]
New array:
[{
"fan_count": 1239,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
"id": "1234567890"
},
{
"fan_count": 4329,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
},
"id": "09876543210"
}, ...
]]
You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:
var currArr = [
{
"fan_count": 1234,
"id": "1234567890",
},
{
"fan_count": 4321,
"id": "09876543210",
},
{
"fan_count": 4321,
"id": "09876543215",
}
];
var newArr = [
{
"fan_count": 1234,
"id": "1234567890"
},
{
"fan_count": 5555,
"id": "09876543210"
}
];
currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
found.fan_count_new = obj.fan_count;
}
});
console.log(currArr);
Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
console.log('found: ', found.fan_count, obj.fan_count)
obj.fan_count_prev = found.fan_count;
obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
}
if (typeof obj.fan_count_prev === "undefined") {
obj.fan_count_prev = obj.fan_count;
obj.fan_count_diff = 0
}
});

Categories

Resources