How to insert key in object based on Id - javascript

I have an array of object, I want to add key in my specifi object of array when Id is matched. I have tried this:
this.data.forEach(value => {
if (value.Id === attachmentDataId) {
AttachmentTypeId: this.attachmentRecord.AttachmentType;
}
});
But it's not working and it's not giving any error also

Try this out :
let data = [{ id: 1 }, { id: 5 }];
const attachmentDataId = 5;
const attachmentRecord = { AttachmentType: "AttachmentType" };
data.forEach(value => {
if (value.id === attachmentDataId) {
value.AttachmentTypeId = attachmentRecord.AttachmentType;
}
});
The stackblitz example: https://stackblitz.com/edit/js-nrhouh

You could use the index parameter of forEach function to access the specific object of the array.
this.data.forEach((value, i) => {
if (value.Id === attachmentDataId) {
this.data[i] = {
...this.data[i],
AttachmentTypeId: this.attachmentRecord.AttachmentType
};
}
});
Inside the if block, you could also instead do
this.data[i]['AttachmentTypeId'] = this.attachmentRecord.AttachmentType;
I just find using the spread operator cleaner.

use javascript map() method.
Map() return a new array, it takes a callback, iterates on each element in that array
const updatedData = data.map(res => {
if(res.id === attachmentDataId) {
res.AttachmentTypeId = attachmentRecord.AttachmentType;
}
return res
})

Related

how to replace modified object in array of objects using react js

i have object structure like this,
[{
"id":"8661c8c96df94ac78283360e0d1c86bd",
"modifiedObject":{....},
"originalObject":{...}
},
{
"id":"1525drd616dr17d78283360e0d1c86bd",
"modifiedObject":null,
"originalObject":{...}
},
{
"id":"6767srsr14542525276767cbd246464",
"modifiedObject":{....},
"originalObject":null
}]
I am finding an object with the id and get the inner object(if modified object present if not original object) and then modifying the data using below code
const originalCopyObject = projObjs.find(s => s.id === projectObjectId);
const targetCopyObject = originalCopyObject.modifiedObject || originalCopyObject.originalObject; // here in this case it always be one either modified or original object
const targetMutatedCopyObject = cloneDeep(targetCopyObject);
if (!targetMutatedCopyObject?.glazingOrGasMaterials.length) {
targetMutatedCopyObject.glazingOrGasMaterials = [
...targetMutatedCopyObject.glazingGasMaterials,
...targetMutatedCopyObject.glazingSimpleMaterials,
];
}
targetMutatedCopyObject.opaqueConstructions.forEach(transformConstructions);
Now targetMutatedCopyObject is having one of the modifiedObject or originalObject, How can I replace this targetMutatedCopyObject object in projObjs.
Could any one please let me know how to replace this tragetMutatedCopyObject in projObjs array of objects.
Many thanks in advance.
Updated Code :
projObjs.map(projObj => {
if (projObj.id === projectObjectId) {
const targetCopyObject = projObj.modifiedObject || projObj.originalObject;
const mutatedCopyObject = transformFormStateToMutationObject(targetCopyObject);
if (projObj.modifiedObject) {
return {
...projObj,
modifiedObject: mutatedCopyObject
};
}
if (projObj.originalObject) {
return {
...projObj,
originalObject: mutatedCopyObject
};
}
return projObj;
}
return projObj;
});
}`
Generally you would copy, or map, the old object to a new object reference. If the id matches the currently mapped element, return new object with the updated/modified properties, otherwise return the current element.
projObjs.map((projObj) => {
if (projObj.id === projectObjectId) {
const targetCopyObject = projObj.modifiedObject || projObj.originalObject;
const targetMutatedCopyObject = cloneDeep(targetCopyObject);
if (!targetMutatedCopyObject?.glazingOrGasMaterials.length) {
targetMutatedCopyObject.glazingOrGasMaterials = [
...targetMutatedCopyObject.glazingGasMaterials,
...targetMutatedCopyObject.glazingSimpleMaterials
];
}
targetMutatedCopyObject.opaqueConstructions.forEach(transformConstructions);
return {
...projObj,
modifiedObject: targetCopyObject
};
}
return projObj;
});
Edit to return updated objects back into their original object keys
Factor the object update logic into a utility function and apply some branching logic on the modifiedObject and originalObject values in order to return an updated object back to the appropriate key.
projObjs.map((projObj) => {
if (projObj.id === projectObjectId) {
const updateObject = (targetCopyObject) => {
const targetMutatedCopyObject = cloneDeep(targetCopyObject);
if (!targetMutatedCopyObject?.glazingOrGasMaterials.length) {
targetMutatedCopyObject.glazingOrGasMaterials = [
...targetMutatedCopyObject.glazingGasMaterials,
...targetMutatedCopyObject.glazingSimpleMaterials
];
}
targetMutatedCopyObject.opaqueConstructions.forEach(
transformConstructions
);
return targetMutatedCopyObject;
};
if (projObj.modifiedObject) {
return {
...projObj,
modifiedObject: updateObject(projObj.modifiedObject)
};
}
if (projObj.originalObject) {
return {
...projObj,
originalObject: updateObject(projObj.originalObject)
};
}
return projObj;
}
return projObj;
});
Note: Be sure to capture the returned result from projObjs.map to update any parent object. This will be the new updated array.

Convert to Object and Adding property to object of array

I want to make filter by date with this object of array
const mapDateRange = () => {for (let elem in catchData) {
let x = {startDate:catchData[elem][0],finishDate:catchData[elem][1]};
return x;
}};
but its only catch one object of array
this is latest data has processing
const data = {
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
};
this is what i expected
const data = [
{
startDate:"01-08-2019", finisDate:"08-08-2019"
},
{
startDate:"08-08-2019", finisDate:"15-08-2019"
},
{
startDate:"15-08-2019", finisDate:"22-08-2019"
},
{
startDate:"22-08-2019", finisDate:"29-08-2019"
}
];
So there are a few problems in the code you wrote:
Your data started as an object ({}), but its built as an array, so I corrected that.
Your function mapDateRange uses catchData but it does not exist anywhere so I made the function except an argument, which will be the catchData.
Most important: You returned x which is only 1 item in the array of data. So I created an empty array and pushed x values to the array.
const data = [
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
];
const mapDateRange = (catchData) => {
let new_data = [];
for (let elem in catchData) {
let x = {
startDate: catchData[elem][0],
finishDate: catchData[elem][1]
};
new_data.push(x);
}
return new_data;
};
console.log(mapDateRange(data));
const data = [
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
];
const mapDataRange = (data) => {
const result = [];
data.forEach((item) => {
const x = { 'startDate': item[0], 'finishDate': item[1] };
result.push(x);
});
return result;
}
console.log(mapDatatRange(data));
In this way you will get your desire result by using map function
data = data.map((obj) => {
return {
startDate: obj[0],
finishDate: obj[1]
}
});
console.log(data)
try to do with .map and array destructuring with ES6 syntax
data.map(([ startDate, finishDate ]) => { startDate, finisDate })

How to get text by id from array? React

CurrentUserAnswerVariants:
{id: "4468cdc8-220d-4634-9d68-6c9920e0cb48", text: "Question 1",
minAnswersQuantity: 1, maxAnswersQuantity: 1, canComment: false,
canComment: false, currentUserAnswerVariants: ["ecc0b93c-8e3b-4661-8f2e-f5382a74d79b"], id: "4468cdc8-220d-4634-9d68-6c9920e0cb48" }
const answers = [];
this.setState({questionGroups}, () => {
this.state.questionGroups.map((questionGroup) => {
questionGroup.questions.map((question) => {
// questionGroup.questions.variants.map((variant) => {
const currentUserAnswerVariantsVariantIds = question.currentUserAnswerVariants.filter(variant => ["canComment"].indexOf(variant) === -1);
const currentUserAnswerVariantsVariantText = question.currentUserAnswerVariants.filter(variant => currentUserAnswerVariantsVariantIds === variant.id).text;
const answer = {
questionId: question.id
};
if (!isNull(question.currentUserAnswerComment)) {
answer["comment"] = question.currentUserAnswerComment;
}
if (currentUserAnswerVariantsVariantIds.length) {
answer["variantIds"] = currentUserAnswerVariantsVariantIds;
}
if (currentUserAnswerVariantsVariantText) {
answer["variantText"] = currentUserAnswerVariantsVariantText;
}
answers.push(answer);
console.log(questionGroup.questions.variants);
// });
});
});
});
};
How to get by currentUserAnswerVariants value text from variants array by id?
My array Please can u see this image where is my array and when i check some variant i have new array Answer array
function idEquals(idToCompare, question) {
return question.id.indexOf(idToCompare) === 0;
}
currentUserAnswerVariantsVariantIds = question.filter(idEquals.bind(this, currentUserAnswerVariants));
Does this work?
It's something along these lines, and you may edit the following code accordingly.
$var = $('#id').val();
$var['text'];
-> only if you need single id text
-> or use foreach on id and push the each result into one blank array and print array

Check all object values inside Array javascript has boolean false

I have below object inside array
[
{
"age":32,
"test":true
},
{
"age":33,
"test":true
},
{
"age":35,
"test":false
}
]
I need to check if all values of test is false.
I have tried below code
Array.isArray(obj.map((message,index) => {
if(message.test !== message.test){
//trigger when all values are false
}
}))
How to achieve this?
You can use every from Array prototype:
let areAllFalse = array.every(x => x.test === false);
You can also you filter from array prototype...
const filtered = array.filter(a => a.test === true)
or the less verbose
const filtered = array.filter(a => a.test)

Javascript Loops: for-loop works but not map?

I'm working with mockData for a web app and I'm trying to loop over nested objects. My problem is that a for loop works but not array.map and don't know why.
Here is the for loop:
for (let i = 0; i < fakeChartData.length; i++) {
for (let j = 0; j < fakeChartData[i].poll.length; j++) {
if (fakeChartData[i].poll[j].id === id) {
return fakeChartData[i].poll[j]
}
}
}
And here is the map loop:
fakeChartData.map(data => {
data.poll.map(data => {
if (data.id === id) {
return data;
}
});
});
My Data structure:
fakeChartData = [
{
id: '232fsd23rw3sdf23r',
title: 'blabla',
poll: [{}, {}]
},
{
id: '23dgsdfg3433sdf23r',
title: 'againBla',
poll: [{}, {}]
}
];
I'm trying to load the specific object with the id passed to it on onClick method.
Here is the full function:
export const fetchPollOptById = (id) =>
delay(500).then(() => {
for (let i = 0; i < fakeChartData.length; i++) {
for (let j = 0; j < fakeChartData[i].poll.length; j++) {
if (fakeChartData[i].poll[j].id === id) {
return fakeChartData[i].poll[j]
}
}
}
});
A return statement inside a for loop causes your function to return. However, a return statement inside a .map() function's callback only returns the callback and this returned value is then placed in the new array. Please see the documentation.If you really want to be using .map(), you could do it like this:
export const fetchPollOptById = (id) => {
var result;
fakeChartData.map(data => {
data.poll.map(data => {
if (data.id === id) {
result = data;
return data;
}
});
});
return result;
}
note: I also assume that your poll objects have an id field like this:
fakeChartData = [
{
id: '232fsd23rw3sdf23r',
title: 'blabla',
poll: [
{id: 'pollId1', otherField: 'blah'},
{id: 'pollId2', otherField: 'blah'}
]
},
{
id: '23dgsdfg3433sdf23r',
title: 'againBla',
poll: [
{id: 'pollId3', otherField: 'blah'},
{id: 'pollId4', otherField: 'blah'}
]
}
];
You can then get the poll data like this:
fetchPollOptById("pollId3"); //returns {id: "pollId3", otherField: "blah"}
If I'm right about what you're trying to do, this should work:
return fakeChartData.reduce((acc, data) => acc.concat(data.poll), [])
.filter(pollObj => pollObj.id === id)[0]
First it makes an array containing all the poll objects from different data objects, then it filters them to find the one with the correct id and returns that object.
As to why your approach using map does not work: you are using it in the wrong way. What map does it to take a function and apply it to every member of an array.
Here's an array and function kind of like yours:
const arr = [1,2,3]
const getThingById(id) => {
var mappedArray = arr.map(x => {
if(x === id) return x
})
console.log(mappedArray) // [3]
}
getThingById(3) // undefined
This won't work. getThingById has no return statement. The return statement return x is returning something from the function that is passed into map. Basically, you shouldn't be using map to do what you're trying to do. map is for when you want to return an array.
Try this
fakeChartData.map(data => {
var result = data.poll.map(data => {
if (data.id === id) {
return data;
}
});
return result;
});
It should work. And yeah you should use find() instead of map() I think.
A bit long implementation:
let results = fakeChartData.map(data => {
let innerResult = data.poll.filter(data => {
if (data.id === id) {
return data;
}
return innerResult.length ? innerResult[0] : null;
});
})
.filter(x => (x !== null));
let whatYouwant = results.lenght ? results[0] : null;
If you can use find() it would look nicer, but that depends on what browsers you need to support

Categories