Editing/Adding value in object of objects - javascript

Main problem is that key format is not supported for selecting.
I do have automatically generated object list with unique keys.
Index and key is known. I do need to add value to custom_property object or edit if it already exists.
Code snapshot:
let initialValue = {
"126ccbb5-1a89-40a9-9393-6849a2f502bc": {
"uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc",
"order": 0,
"custom_properties": {
},
},
"82945a12-ffcb-4dba-aced-e201fa9a531e": {
"uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e",
"order": 1,
"custom_properties": {
},
}
}
I do have these values that I want to insert/update on the custom_property array
const index = 0;
const name = "some_title"
const value = {value: 1, label: "some label"}
How result should look like:
let initialValue = {
"126ccbb5-1a89-40a9-9393-6849a2f502bc": {
"uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc",
"order": 0,
"custom_properties": {
"some_title" : {value: 1, label: "some label"}
},
},
"82945a12-ffcb-4dba-aced-e201fa9a531e": {
"uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e",
"order": 1,
"custom_properties": {
},
}
}

You can try using Object.values() and get the array of items and then pass down the index like,
Object.values(data)[index]
Then assign the dynamic key-value to the custom_properties like,
item.custom_properties = {
[name]: value,
};
Working Snippet:
let initialValue = {
'126ccbb5-1a89-40a9-9393-6849a2f502bc': {
uuid: '126ccbb5-1a89-40a9-9393-6849a2f502bc',
order: 0,
custom_properties: {},
},
'82945a12-ffcb-4dba-aced-e201fa9a531e': {
uuid: '82945a12-ffcb-4dba-aced-e201fa9a531e',
order: 1,
custom_properties: {},
},
};
const index = 0;
const name = 'some_title';
const value = { value: 1, label: 'some label' };
const getUpdatedResult = (data) => {
const item = Object.values(data)[index];
if (item) {
item.custom_properties = {
[name]: value,
};
}
return data;
};
console.log(getUpdatedResult(initialValue));

you can do something like this
const update = (data, index, key, value) =>
Object.fromEntries(Object.entries(data).map(([k, v], i) => i === index? [k, {...v, custom_properties: Object.assign({}, v.custom_properties, {[key]: value})}]:[k,v]))
let initialValue = {
"126ccbb5-1a89-40a9-9393-6849a2f502bc": {
"uuid": "126ccbb5-1a89-40a9-9393-6849a2f502bc",
"order": 0,
"custom_properties": {},
},
"82945a12-ffcb-4dba-aced-e201fa9a531e": {
"uuid": "82945a12-ffcb-4dba-aced-e201fa9a531e",
"order": 1,
"custom_properties": {},
}
}
const newValue = update(initialValue, 0, 'newKey', 'newValue')
console.log(newValue)

Related

how to convert an object to array of objects

I have data in the following format
const data =
{
"sent_total":429,
"sent_distribution":[
{
"date_triggered__date":"2022-12-07",
"count":92
},
{
"date_triggered__date":"2022-12-08",
"count":337
}
],
"delivered":428,
"delivered_distribution":[
{
"timestamp__date":"2022-12-07",
"count":91
},
{
"timestamp__date":"2022-12-08",
"count":337
}
],
}
Need help in converting this in the following format which separates the data by the key (which is sent or delivered) to an array of objects.
const data = [
{
key: sent,
value: 429,
distribution: [
{
date_triggered__date: "2022-12-07",
count: 92,
},
{
date_triggered__date: "2022-12-08",
count: 337,
},
],
},
];
Hope it helps:
const data =
{
"sent_total":429,
"sent_distribution":[
{
"date_triggered__date":"2022-12-07",
"count":92
},
{
"date_triggered__date":"2022-12-08",
"count":337
}
],
"delivered":428,
"delivered_distribution":[
{
"timestamp__date":"2022-12-07",
"count":91
},
{
"timestamp__date":"2022-12-08",
"count":337
}
],
}
const result = [];
Object.keys(data).map((key) => {
const newKey = key.split("_")[0];
let index = result.findIndex((resultItem) => resultItem.key === newKey);
const value = key.includes("_distribution") ? null : data[key];
const distribution = key.includes("_distribution") ? data[key] : null;
if(index === -1) {
result.push({
key: newKey,
value: value,
distribution: distribution
});
} else {
if(value)
result[index].value = value;
if(distribution)
result[index].distribution = distribution;
}
});
console.log(result);

Conversion of array of object to object

I have an array of objects:
const action_triggers = [
{
onClick: {
action_id: "1",
},
},
{
onLoad: {
action_id: "2",
},
},
];
How do I convert it into the following by JavaScript?
const action_trigger = {
onClick: {
action_id: 1
},
onLoad: {
action_id: 2
}
}
Here is the reduce version
const _l = (s) => {
console.log(s);
};
let flatter = action_triggers.reduce((propogator, prop) => {
for (const [key, value] of Object.entries(prop)) {
propogator[key] = value;
}
return propogator;
}, {});
_l(flatter);
Helps with conditionally doing whatever you want to {} the input

Comparing property of object with property of another array

I am having difficulty comparing properties of two objects/arrays
First object
{
"62ac1c8d5b25ad28781a586d": {
"selectedOption": 0
},
"62ac1c8d5b25ad28781a586e": {
"selectedOption": 0
}}
Second Array
[
{
"question_id": "62ac1c8d5b25ad28781a586d",
"selected_ans": 0
},
{
"question_id": "62ac1c8d5b25ad28781a586e",
"selected_ans": 0
},
{
"question_id": "62ac1c8d5b25ad28781a586f",
"ans": 0
}
]
Kindly suggest how to compare the initial property of first object(example: 62ac1c8d5b25ad28781a586d) with the question_id property of second array and return only the matching question_id
You can filter elements from secondArr using Set as:
const obj = {
'62ac1c8d5b25ad28781a586d': {
selectedOption: 0,
},
'62ac1c8d5b25ad28781a586e': {
selectedOption: 0,
},
};
const secondArr = [
{
question_id: '62ac1c8d5b25ad28781a586d',
selected_ans: 0,
},
{
question_id: '62ac1c8d5b25ad28781a586e',
selected_ans: 0,
},
{
question_id: '62ac1c8d5b25ad28781a586f',
ans: 0,
},
];
const keys = new Set(Object.keys(obj));
const result = secondArr.filter((o) => keys.has(o.question_id));
console.log(result);
You could simply use the find method defined on the array prototype.
function compare(id, arr){
return arr.find(arrObj => arrObj.question_id === id);
}
To find all the matching ids from the object present in the array, you could loop through the keys and call the compare function for those keys like this.
function compare(id, arr) {
return arr.find(arrObj => arrObj.question_id === id);
}
const obj = {
"62ac1c8d5b25ad28781a586d": {
"selectedOption": 0
},
"62ac1c8d5b25ad28781a586e": {
"selectedOption": 0
}
}
const arr = [
{
"question_id": "62ac1c8d5b25ad28781a586d",
"selected_ans": 0
},
{
"question_id": "62ac1c8d5b25ad28781a586e",
"selected_ans": 0
},
{
"question_id": "62ac1c8d5b25ad28781a586f",
"ans": 0
}
]
const matchingObjects = [];
for (let key in obj) {
const matchObject = compare(key, arr);
if (matchObject) {
matchingObjects.push(matchObject);
}
}
console.log(matchingObjects);

In typescript the filtering the array is not working

filtervalue = {
serviceLine:['cca','ga']
}
this.inProgresDetailsData = [{serviceLine:'cca'}, { serviceLine:'cca'}, { serviceLine:'bca'}]
this.hrResourceDetailsdata= this.inProgresDetailsData.filter(item => {
for (let index = 0; index < filterValue.serviceLine.length; index++) {
item.serviceLine == filterValue.serviceLine[index]
}
});`
this.hrResourceDetailsdata is empty on filtering
The Array.prototype.filter (documentation) function expects you to return a boolean value that decides whether to keep the current item or not.
Since you are originally not returning any value, you implicitly return undefined which when checked against a boolean resolves to false, hence, all of your array items are discarded one by one, leaving none remaining.
You want to return the boolean to make this work:
this.hrResourceDetailsdata = this.inProgresDetailsData.filter(item => {
for (let index = 0; index < filterValue.serviceLine.length; index++) {
if (item.serviceLine == filterValue.serviceLine[index]) {
return true; // return true if found, otherwise continue
}
}
return false; // filter is never found in loop, fall back to false
});
Also, you can use Array.prototype.includes (documentation) to simplify your check, the following code does the exact same thing:
this.hrResourceDetailsdata = this.inProgresDetailsData.filter(item => {
// return true if `item.serviceLine` is inside `filterValue.serviceLine`
return filterValue.serviceLine.includes(item.serviceLine);
});
You can create a Set out of filterValue.serviceLine and filter out the items that are present in the set.
const
filterValue = { serviceLine: ["cca", "ga"] },
inProgressDetailsData = [
{ serviceLine: "cca" },
{ serviceLine: "cca" },
{ serviceLine: "bca" },
],
filterSet = new Set(filterValue.serviceLine),
hrResourceDetailsdata = inProgressDetailsData.filter(({ serviceLine }) =>
filterSet.has(serviceLine)
);
console.log(hrResourceDetailsdata);
If you want to apply multiple filters, then:
Create an object containing filters in form of Sets.
Filter items where all the filters are applicable using Array.prototype.every.
const
filterValue = {
serviceLine: ["cca", "ga"],
urgency: ["medium", "high"],
},
filterSet = Object.fromEntries(
Object.entries(filterValue).map(([k, v]) => [k, new Set(v)])
),
inProgressDetailsData = [
{ id: 1, urgency: "low", serviceLine: "cca" },
{ id: 2, urgency: "medium", serviceLine: "cca" },
{ id: 3, urgency: "low", serviceLine: "bca" },
{ id: 4, urgency: "high", serviceLine: "ga" },
{ id: 5, urgency: "low", serviceLine: "abc" },
],
hrResourceDetailsdata = inProgressDetailsData.filter((data) =>
Object.entries(filterSet).every(([k, v]) => v.has(data[k]))
);
console.log(hrResourceDetailsdata);
Code
filtervalue = {
serviceLine:['cca','ga']
};
this.inProgresDetailsData = [
{ serviceLine:'cca'},
{ serviceLine:'cca'},
{ serviceLine:'bca'}
];
this.hrResourceDetailsdata = this.inProgresDetailsData.filter(item => {
return filtervalue.serviceLine.includes(item.serviceLine)
});
console.log(this.hrResourceDetailsdata)

Attempting to transform a javascript object into an array with multiple nests

I have a javascript object containing:
var object =[{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0},{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0}
const keyname = ['eventHeader'];
const result = keyname.reduce((acc, date, i) => {
acc.push([keyname, data]);
return acc;
}, []);
var json_object = JSON.stringify(result);
document.getElementById("Object").innerHTML = json_object;
$('.result').append('<div id ="alert" class="alert-success"><ul class="list-group" min-width:500px><li class="list-group-item active">Result Json</li><textarea class="form-control" cols="100" rows="10">{"records:"['+json_object+'</textarea></li></div>');
})
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsBinaryString(selectedFile);
});
});
The output required is:
{
"records": [
{
"common": {
"validTime": "20180101T121222",
"knowledgeTime": "20180101T121222"
},
"eventHeader": {
"portfolioId": "Collect Acquisition Disposition Transactions",
"type": "EQUITY_OPEN_LONG"
},
"details": {
"assetId": 12,
"custodianAccountId": 0,
"strategyId": 0,
"quantity": 150,
"cost": 5001.23,
"contractualSettleDate": "SPECIAL",
"commission": 2.05,
"fee": 1.03,
"managerId": 0,
"basketId": 0
}
}
but what I am getting is nothing close as I do not understand how to splice the needed 3 array keys into the proper spots in the object.
If anyone could assist? The closest I have been ablo to get is to push an eventHeader key into the object - but without being able to figure out how to concat the portfolioId key value pair into it. Sorry if this is too noob - but I'm really strugging to understand the language. I had another version where I attempted a regex replace in the stringify but that didn't work either I'm assuming I need to pull in each object row - splice in the keys followed by the key value pairs - but can't figure out splice.
The solution is:
var object =[{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0},{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0}];
const getObject = (array) => {
const newArray = array.map(obj => {
const { validTime, knowledgeTime, portfolioId, type, assetId, custodianAccountId, strategyId, quantity, cost, contractualSettleDate, commission, fee, managerId, basketId } = obj;
const newObject = {
common: {
validTime,
knowledgeTime
},
eventHeader: {
portfolioId,
type
},
details: {
assetId,
custodianAccountId,
strategyId,
quantity,
cost,
contractualSettleDate,
commission,
fee,
managerId,
basketId
}
};
return newObject;
})
return { records: newArray };
}
const requeiredOutput = getObject(object);
console.log(requeiredOutput);
I'm not 100% sure of what you're trying to do, but if it's what I think it is then this is a solution:
const sourceArray = [
{
knowledgeTime: '20180101T235959',
validTime: '20180101T235959',
portfolioId: 'Control',
type: 'EQUITY_OPEN_LONG',
assetId: 'A',
strategyId: 0,
quantity: 1000,
cost: 100000,
contractualSettleDate: 'SPECIAL',
commission: 2.06,
fee: 1.03,
managerId: 0,
},
{
knowledgeTime: '20180101T235959',
validTime: '20180101T235959',
portfolioId: 'Control',
type: 'EQUITY_OPEN_LONG',
assetId: 'A',
strategyId: 0,
quantity: 1000,
cost: 100000,
contractualSettleDate: 'SPECIAL',
commission: 2.06,
fee: 1.03,
managerId: 0,
},
];
const commonKeys = ['validTime', 'knowledgeTime'];
const eventHeaderKeys = ['portfolioId', 'type'];
function createNestedObj(obj) {
const nestedObj = {common: {}, eventHeader: {}, details: {}};
for (const [key, val] of Object.entries(obj)) {
if (commonKeys.includes(key)) {
nestedObj.common[key] = val;
} else if (eventHeaderKeys.includes(key)) {
nestedObj.eventHeader[key] = val;
} else {
nestedObj.details[key] = val;
}
}
return nestedObj;
}
const output = {records: []};
for (const item of sourceArray) {
const nestedObj = createNestedObj(item);
output.records.push(nestedObj);
}
console.log(output);

Categories