Converting object to array within an object in JavaScript - javascript

I am getting back data in a format that is not acceptable to the processing system and I am trying to convert the data. Below is the data I get and the required JSON below that. I tried different things like finding an Object within the data and checking if it has more than one element then converting that object to Array[] but I am unable to do so.
If you have any inputs, I would appreciate it.
if(typeof ob1=== "object" && Object.keys(ob1.length > 1) && typeof Object.keys(ob1) === "object" )
{
console.log(ob1); // I get all the objects and not the parent object i need to change.
}
Present data:
ob1 : {id: 1, details: Object, profession: "Business"}
JSON:
{
"id": "1",
"details": {
"0": {
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
"1": {
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
},
"profession": "Business"
}
Required data:
{id: 1, details: Array[2], profession: "Business"}
Required JSON:
{
"id": "1",
"details": [
{
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
{
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
],
"profession": "Business"
}

You have to go through the details object and convert it into an array:
var x = {
details: {
0: {a: 1},
1: {a: 2}
}
}
var detailsArr = [];
for(key in x.details) {
detailsArr.push(x.details[key]);
}
x.details = detailsArr;
//x.details = [{a: 1}, {a: 2}]

Related

How can I concatenate this type of JSON in javascript?

How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.

How to compare elements in array objects using javascript

I am new to javascript usage.
I have a requirement to compare the field from two different array objects which are having list as below.
Array - A
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
]
Array - B
[
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
}
,
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
]
The scenario is to compare for each 'id' in the list of array A, with the list of Array B to field 'id1'
Example -
I need to check from Array A -> 'id:xyz' matches the array B object field 'id1'.
Array A - id: xyz should match with id1: xyz in Array B
If the match occurs I need to pull out complete object from the array list A.
here id:xyz matches with id1:xyz
then pull out as below
[
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
}
]
Please help me with the suggestions to make this work using javascript.
const A = [
{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const B = [
{
"element1" : "ert",
"id1":"iii",
"element2":"erws",
"element3":"234"
},
{
"element1" : "uio",
"id1":"xyz",
"element2":"puy",
"element3":"090"
}
];
const C = A.filter(a => B.some(b => b.id1 === a.id));
console.log(C);
// the usage of `const` here means that arrA cannot be re-declared
// this is good for data that should not be changed
const arrA = [{
"id": "xyz",
"number": "123",
"place": "Here",
"phone": "9090909090"
},
{
"id": "abc",
"number": "456",
"place": "There",
"phone": "9191919191"
},
];
const arrB = [{
"element1": "ert",
"id1": "iii",
"element2": "erws",
"element3": "234"
},
{
"element1": "uio",
"id1": "xyz",
"element2": "puy",
"element3": "090"
}
];
// slow method for long lists, fine for short lists or if there are duplicates
// compares each entry in array A to each entry in array B
const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1));
console.log("Example 1: \n", out1);
// faster for long lists
// creates a set of unique values for array B's id1 parameter, ignores duplicates
// then checks that set for each entry in array A
const setB = arrB.reduce((a, b) => {
a.add(b.id1);
return a;
}, new Set());
const out2 = arrA.filter(x => setB.has(x.id));
console.log("Example 2: \n", out2)
.as-console-wrapper { min-height: 100% } /* this is just to make the stack overflow output prettier */

Make v-card selectable/toggle-able and pass an object to an array in Vue

I currently have some cards that each hold a value. I want to basically make each card act like a toggle button and when the card is toggled on I want that cards value to be added to the array.
I currently use:
#click="selectableCards( {Group: `${user.GroupHex}`, UserID: user.UserIDInt, SuperID: `${user.SuperID}`} )"
to pass the data to my function:
selectableCards(x) {
if(this.array.includes(x)) {
console.log('prop already exists inside array')
} else {
this.array.push(x)
}
console.log(this.array)
}
Whenever I use this the object is added to the array but it will allow me to add the same object over and over again. It doesn't detect that the object is already in the array.
So again basically I want the #click on the card to act like a toggle button to add or remove the data inside the card.
An example of 3 cards values into an array:
[ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]```
You cannot cannot compare objects same way as primitives in javascript:
const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]
console.log(objects.includes({ "Group": "10", "UserID": 6, "SuperID": "2566" }))
For more information about that take a look here: Object comparison in JavaScript
However what you can do is to search for an element in an array based on some conditions for example with array.find() -method like so:
const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ];
const matchedObject = objects.find((object) => {
return object.Group === "10" &&
object.UserID === 6 &&
object.SuperID === "2566"
});
console.log(matchedObject);
If you just need to know if a card is selected send a string/number to selectableCards instead of an object and your function doesn't have to change.
#click="selectableCards(user.UserID)"
OR
#click="selectableCards(user.SuperID)"
If however you need to store the object I would recommend using findIndex instead of includes
if(this.array.findIndex(temp => {
return temp.Group == x.Group && temp.UserID == x.UserID && temp.SuperID == x.SuperID
})>-1)
...the rest of the code is unchanged

Filtering nested array of objects

I have the following events array. For every event there is a hash as {organisation name: [{participant 1}, {participant 2}, {...}]}
"events": [
{
"Org A": [
{
"event_id": 1,
"id": 432,
"name": "John Doe",
"role": null
},
{
"event_id": 1,
"id": 312,
"name": "Jane Mow",
"role": [
"speaker"
]
}
],
}
],
I would like to filter this events array to only contain participants whose role contains speaker.
Also, when there are no speakers in the participant array, the respective organisation entry needs to be removed from the Hash (object).
To filter the array of objects, I tried using this:
_.each(events, function(event){
_.filter(event, function(p) {
_.filter(p, function(d){
return _.some(d.role, function(r){
return r == "speaker"})
})
})
})
This however doesn't work.
Try this
var data = {
"events": [{
"Org A": [{
"event_id": 1,
"id": 432,
"name": "John Doe",
"role": null
}, {
"event_id": 1,
"id": 312,
"name": "Jane Mow",
"role": [
"speaker"
]
}],
"Org B": [],
"Org C": []
}]
};
var SPEAKER = 'speaker';
var result = _.map(data.events, function (events) {
return _.chain(events)
.mapObject(function (value, key) {
return _.filter(value, function (event) {
return _.isArray(event.role) && _.indexOf(event.role, SPEAKER) >= 0;
});
})
.pick(function (value) {
return value && value.length;
})
.value();
})
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

How to extend an object while ignoring null values?

Say for example I have an object of
var user = {
"Name": "Dan",
"Age": 27,
"Hobbies": null
};
which I would like to merge onto the following base object so that my user object will have all the required properties
var base = {
"Name": null,
"Height": null,
"Age": null,
"Hobbies": [
{ "Name": "Tennis", "Location": null },
{ "Name": "Football", "Location": null },
{ "Name": "Rugby", "Location": null }
]
};
The easiest way to merge to the two objects would be to extend the base object with the user object as follows
$.extend(true, base, user);
which would modify the base object to be
{
"Name": "Dan",
"Height": null,
"Age": 27,
"Hobbies": null
};
My question would be how can I get the extend method to not override null values? For example, in this instance, how can I still obtain a list of hobbies if the users hobby list is null so I end up with the following
{
"Name": "Dan",
"Height": null,
"Age": 27,
"Hobbies": [
{ "Name": "Tennis", "Location": null },
{ "Name": "Football", "Location": null },
{ "Name": "Rugby", "Location": null }
]
};
You may use undefined as value which will be ignored by jQuery.extend.
var user = { "Name": "Dan",
"Age:" 27,
"Hobbies": undefined
};
$.extend(true, base, user);

Categories