Conversion of array of object to object - javascript

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

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);

Get the difference object from two object in typescript/javascript angular

I am trying to get the change object from two objects using typescript in angular.
For example
this.productPreviousCommand = {
"id": "60f910d7d03dbd2ca3b3dfd5",
"active": true,
"title": "ss",
"description": "<p>ss</p>",
"category": {
"id": "60cec05df64bde4ab9cf7460"
},
"subCategory": {
"id": "60cec18c56d3d958c4791117"
},
"vendor": {
"id": "60ced45b56d3d958c479111c"
},
"type": "load_product_success"
}
model = {
"active": true,
"title": "ss",
"description": "<p>ss sss</p>",
"category": "60cec05df64bde4ab9cf7460",
"subCategory": "60cec18c56d3d958c4791117",
"vendor": "60ced45b56d3d958c479111c",
"tags": []
}
Now the difference between two objects are description: "<p>hello hello 1</p>". So I want to return {description: "<p>hello hello 1</p>"}
I used lodash https://github.com/lodash/lodash
import { transform, isEqual, isObject, isArray} from 'lodash';
function difference(origObj, newObj) {
function changes(newObj, origObj) {
let arrayIndexCounter = 0
return transform(newObj, function (result, value, key) {
if (!isEqual(value, origObj[key])) {
let resultKey = isArray(origObj) ? arrayIndexCounter++ : key
result[resultKey] = (isObject(value) && isObject(origObj[key])) ? changes(value, origObj[key]) : value
}
})
}
return changes(newObj, origObj)
}
This library is not working for me, it returns the whole object using this code const differenc = difference(this.productPreviousCommand, model);
The output of above code is
{
active: true
description: "<p>hello hello 1</p>"
id: "60f8f29dd03dbd2ca3b3dfd1"
title: "hello"
}
Try this function
differenceInObj(firstObj: any, secondObj: any): any {
let differenceObj: any = {};
for (const key in firstObj) {
if (Object.prototype.hasOwnProperty.call(firstObj, key)) {
if(firstObj[key] !== secondObj[key]) {
differenceObj[key] = firstObj[key];
}
}
}
return differenceObj;
}
You can check loop through each key of the first object and compare it with the second object.
function getPropertyDifferences(obj1, obj2) {
return Object.entries(obj1).reduce((diff, [key, value]) => {
// Check if the property exists in obj2.
if (obj2.hasOwnProperty(key)) {
const val = obj2[key];
// Check if obj1's property's value is different from obj2's.
if (val !== value) {
return {
...diff,
[key]: val,
};
}
}
// Otherwise, just return the previous diff object.
return diff;
}, {});
}
const a = {
active: true,
description: '<p>hello</p>',
id: '60f8f29dd03dbd2ca3b3dfd1',
title: 'hello',
};
const b = {
active: true,
description: '<p>hello hello 1</p>',
id: '60f8f29dd03dbd2ca3b3dfd1',
title: 'hello',
};
const c = {
active: true,
description: '<p>hello hello 2</p>',
id: '60f8f29dd03dbd2ca3b3dfd1',
title: 'world',
};
console.log(getPropertyDifferences(a, b));
console.log(getPropertyDifferences(b, c));
function difference(origObj, newObj) {
const origObjKeyList = Object.keys(origObj),
newObjKeyList = Object.keys(newObj);
// if objects length is not same
if (origObjKeyList?.length !== newObjKeyList?.length) {
return;
}
// if object keys some difference in keys
if (Object.keys(origObj).filter((val) => !Object.keys(newObj).includes(val))?.length) {
return;
}
return Object.entries(origObj).reduce(
(acc, [key, value]) => (newObj[key] !== value ? { ...acc, ...{ [key]: newObj[key] } } : acc),
[]
);
}
const a = {
active: true,
description: '<p>hello</p>',
id: '60f8f29dd03dbd2ca3b3dfd1',
title: 'hello',
};
const b = {
active: true,
description: '<p>hello hello 1</p>',
id: '60f8f29dd03dbd2ca3b3dfd1',
title: 'hello',
};
console.log(difference(a, b));
You can try this code.
function difference(origObj, newObj) {
const origObjKeyList = Object.keys(origObj),
newObjKeyList = Object.keys(newObj);
// if objects length is not same
if (origObjKeyList?.length !== newObjKeyList?.length) {
return;
}
// if object keys is not same
if (Object.keys(origObj).filter((val) => !Object.keys(newObj).includes(val))?.length) {
return;
}
return Object.entries(origObj).reduce(
(acc, [key, value]) => (newObj[key] !== value ? { ...acc, ...{ [key]: newObj[key] } } : acc),
[]
);
}

How do I convert Array of object key value to Object in object key value

I'm trying to reduce and array of object(key-value) to one object(key-value).
I'm working with a json object injavascript
I have this:
"relations":
[
{"609e598ad32e90519043f09f": "609d8b78cf7bb100045fc593"},
{"609e5945d32e90519043f09e": "609d8b78cf7bb100045fc593"},
{"609e58b496d43235884e788f": "609d8b78cf7bb100045fc593"},
{"609e57e3e1560e58245544f4": "609d8de9575b49000466e358"}
],
And below is my expected result:
"relations":
{
"609e598ad32e90519043f09f":"609d8b78cf7bb100045fc593",
"609e5945d32e90519043f09e":"609d8b78cf7bb100045fc593",
"609e58b496d43235884e788f":"609d8b78cf7bb100045fc593",
"609e57e3e1560e58245544f4":"609d8de9575b49000466e358"
}
How can I achieve this result?
You can use for..in loop to get the key-value and using reduce to store it into an object. Then you can assign it to relations property.
let obj = {
relations: [
{ "609e598ad32e90519043f09f": "609d8b78cf7bb100045fc593" },
{ "609e5945d32e90519043f09e": "609d8b78cf7bb100045fc593" },
{ "609e58b496d43235884e788f": "609d8b78cf7bb100045fc593" },
{ "609e57e3e1560e58245544f4": "609d8de9575b49000466e358" },
],
};
const result = obj.relations.reduce((acc, curr) => {
for (let key in curr) {
acc[key] = curr[key];
}
return acc;
}, {});
obj.relations = result;
console.log(obj);
You can also clone the object and change only the relations key using object destructuring
let obj = {
name: "test",
relations: [
{ "609e598ad32e90519043f09f": "609d8b78cf7bb100045fc593" },
{ "609e5945d32e90519043f09e": "609d8b78cf7bb100045fc593" },
{ "609e58b496d43235884e788f": "609d8b78cf7bb100045fc593" },
{ "609e57e3e1560e58245544f4": "609d8de9575b49000466e358" },
],
};
const result = obj.relations.reduce((acc, curr) => {
for (let key in curr) {
acc[key] = curr[key];
}
return acc;
}, {});
const cloneWithChanges = { ...obj, relations: result };
console.log(cloneWithChanges);

Pass quoted variable to function in React

I would like to pass a quoted variable to a react function. So in the example I would like to have "mq" replaced with a $name variable including double quotes. Instead of this:
if (test === "PER") {
var aggs = () => ({
aggs: {
"mq": {
significant_terms: {
field: feld,
percentage: {},
size: 10
}
},
},
});
}
I would like to have the following:
if (test === "PER") {
var aggs = () => ({
aggs: {
"MQTT": {
significant_terms: {
field: feld,
percentage: {},
size: 10
}
},
},
});
}
Where "MQTT" comes from a variable, e.g. let name="MQTT"; because this part is variable in my Application... But i have no clue on how to pass that name variable to the var aggs=() =>correctly. Hope somebody can help me :(
let name = 'MQTT'
if (test === 'PER') {
var aggs = () => ({
aggs: {
[name]: {
significant_terms: {
field: feld,
percentage: {},
size: 10
},
},
},
})
}
I know it is answered already. However, as a suggestion you can follow this answer.
For any dynamic key in the object you can use [key]. Below are a few examples.
let obj = {
["test"]: "test",
};
console.log(obj); // { test: 'test' }
const key = "test2";
obj = {
[key]: key,
};
console.log(obj); // { test2: 'test2' }
const key3 = "test3";
obj = {};
obj[key3] = key3;
console.log(obj); // { test3: 'test3' }
For your question:
function aggregatorBuilder(test) {
var aggs = null;
if (test === "PER") {
aggs = (key) => ({
aggs: {
[key]: { // dymanic key
significant_terms: {
field: feld,
percentage: {},
size: 10,
},
},
},
});
}
return aggs;
}

Cant access data inside nested array of objects

I have an array of objects that I want to iterate over and create a new array of objects.
First I map over the data, then I loop through each object to extract the values. I want to store the Location name and value from each object.
My code is returning null results. I can't change the way data is declared. Can someone help me understand why I keep getting null results?
[
{
"euValue": null,
"asValue": null
}
]
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
let euValue, asValue;
formattedData = data.map(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
euValue = _this.Location === "Europe" ? _this.Value : null;
asValue = _this.Location === "Asia" ? _this.Value : null;
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
Edit
Expected result is
[
{
"euValue": “Ireland”,
"asValue": “China”
}
]
Assuming that inside data you could have multiple objects with a Location array that have only 2 objects (one for Europe and another one for Asia) you should change your function to something like this
const data = [
{
Locations: [
{
Location: { Name: "Europe" },
Value: "Ireland"
},
{
Location: { Name: "Asia" },
Value: "China"
}
]
}
];
const formatData = () => {
// iterate all data objects
return data.map((topLocation) => {
const res = {};
// loop over Location children objects
topLocation.Locations.forEach((location) => {
const { Name } = location.Location;
// decide where to save Value base on the Location.name
if (Name === "Europe") {
res.euValue = location.Value;
} else if (Name === "Asia") {
res.asValue = location.Value;
}
});
return res;
});
};
const newData = formatData();
console.log(newData);
you missing a second loop also you overwriting the usValue and euValue and you better use forEach instead of map in this case.
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = (data) => {
let formattedData = [],
values = {};
data.forEach(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
_this.forEach(el => {
if (el.Location.Name === "Europe") {
values["euValue"] = el.Value || null
}
if (el.Location.Name === "Asia") {
values["asValue"] = el.Value || null
}
})
}
}
});
formattedData.push(values)
return formattedData;
};
console.log(formatData(data))
I don't know what do you want to get from your code but this code may help you.
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
formattedData = data.map(location => {
let euValue = [],
asValue = [];
for (const l in location.Locations) {
if (location.Locations.hasOwnProperty(l)) {
const _this = location.Locations[l];
if (_this.Location.Name === "Europe")
euValue.push(_this.Value);
else if (_this.Location.Name === "Asia")
asValue.push(_this.Value);
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
I'm sure many of the other answers are fine but the way I did it was to do the classic for loop to iterate over the data. I would have liked to have kept your ternary operators but I think you may need the if/else syntax.
var data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
let formattedData = [];
let euValue, asValue;
formattedData = data.map(location => {
for (const l in location) {
if (location.hasOwnProperty(l)) {
const _this = location[l];
for (let i = 0; i < _this.length; i++) {
if (_this[i].Location.Name === "Europe") {
euValue = _this[i].Value;
} else if (_this[i].Location.Name === "Asia") {
asValue = _this[i].Value;
} else {
euValue, asValue = null;
}
}
}
}
return {
euValue,
asValue
};
});
return formattedData;
};
const newData = formatData();
console.log(newData);
Using Array.prototype.flatMap() might help you get the array you desire in a cleaner way:
const data = [{
Locations: [{
Location: {
Name: "Europe"
},
Value: "Ireland"
},
{
Location: {
Name: "Asia"
},
Value: "China"
}
]
}];
const formatData = () => {
const formattedData = data.flatMap(item => {
const object = {}
item.Locations.map(location => {
const continent = location.Location.Name
let country = {}
if (continent === 'Europe') country = {
euValue: location.Value
}
if (continent === 'Asia') country = {
asValue: location.Value
}
Object.assign(object, country)
});
return object
});
return formattedData;
}
const newData = formatData();
console.log(newData);

Categories