I am trying to achieve a data structure in javascript that looks like this:
settings: {
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
The amount of keys is variable and needs to be iterated over. I thought I could do it with an array but the [0] numbers are getting in the way.
This is what i have now:
convertSettingsToApiSaveFormat(values) {
const keys = Object.keys(values);
const items = Object.values(values);
const valuesToSend = keys.map((key, i) => {
return { key, value: items[i] };
});
return { settings: [valuesToSend] };
}
}
Which returns:
any help is much appreciated!
First of all this is an invalid data structure
settings: {
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
JavaScript object is bascally key value pair you can see the bellow two objects dont have and key.
Either it can be like this
settings: {
"someKey": { "key": "Language", "value": "en" },
"someKey2": { "key": "Language", "value": "en" }
}
or a simple JS array
settings: [
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
]
You're placing valuesToSend inside an array - remove it, and you'll get your desired output*:
return { settings: valuesToSend };
* The result you currently want is invalid - this, however, is valid:
settings: [
{ "key": "Language", "value": "en" },
{ "key": "Language", "value": "en" }
}
Related
I'm trying to convert the Cognito user attributes I get from CognitoIdentityServiceProvider listUsersInGroup to plain object but I didn't found any library or AWS function that does it... then I tried to implement it by myself
That's what I came up with:
{
...user,
Attributes: user.Attributes.map((x) => ({ [x.Name]: x.Value })),
}
But that makes an array with objects and I'm trying to create an object with all the attributes...
[
{
"sub": "dasfdasfd-vcfdgfd",
},
{
"website": "aba",
},
{
"address": "new",
},
]
here is an example of the user's data (the attributes can be different from user to user):
user a:
[
{
"Name": "sub",
"Value": "dasfdasfd-vcfdgfd",
},
{
"Name": "website",
"Value": "aba",
},
{
"Name": "address",
"Value": "new",
},
{
"Name": "email_verified",
"Value": "false",
},
{
"Name": "phone_number_verified",
"Value": "false",
}
]
user b:
[
{
"Name": "custom:age",
"Value": "0",
},
{
"Name": "custom:height",
"Value": "0",
},
{
"Name": "email",
"Value": "dsafdsa#gmail.com",
}
]
You can use reduce
{
...user,
Attributes: user.Attributes.reduce((acc, { Name, Value }) => ({...acc, [Name]: Value }), {}),
}
Seems pretty simple just use loop. FYI : Array's map function always returns the array
function getAttributes(data){
let attributes = {};
for(let x of data){
attributes[x["name"]] = x["value"];
}
return attributes;
}
{
...user,
Attributes: getAttributes(user.Attributes)
}
I have a value that I am searching for. I would like to match the term I am searching for to the value of the key and return the value for the key of name associated with the same object.
Here is a sample object:
{
"test1": {
"functions": {
"function1": {
"inputs": [
{
"key": "key1",
"name": "name1"
},
{
"key": "key2",
"name": "name3"
},
{
"key": "key3",
"name": "name3"
}
]
},
"function2": {
"inputs": [
{
"key": "key4",
"name": "name4"
},
{
"key": "key5",
"name": "name5"
},
{
"key": "key6",
"name": "name6"
}
]
}
}
}
}
Let's say I want to find the name of an input with a key of key4. How would I achieve this in javascript?
You only have to iterate the individual objects inside of the "inputs" array and check, whether the key property is "key4"
var inputs = []; // you would have to get the individual lists
inputs.forEach(function (input) {
if (input['key'] === 'key4') {
// do something with input['name'];
}
});
optimally you would make a function, that returns the input['name']
I have the following response from the server. I need to search this answer and compare it in turn with each field.
Example:
My task is that I know for sure that there should be 3 objects and each object has its own value for the type field, this is 'API', 'DEFAULT' or 'X'. How can you make it so that you can search for these three values in the whole object and get an error if one of them is missing?
{
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "Х"
}
],
"success": true
}
You can first verify that the length is 3 and then loop over all the types and check if each one is present.
const data = {
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "Х"
}
],
"success": true
};
const requiredTypes = ['API', 'DEFAULT', 'Х'];
const types = new Set(data.result.map(({type})=>type));
const good = data.result.length === 3 && requiredTypes.every(type=>types.has(type));
console.log(good);
In case you would like to also know which value of those 3 are missing:
const check = (obj) => {
if (obj.result.length !== 3) return false;
let validTypes = ['API', 'DEFAULT', 'X'];
obj.result.forEach((r) => {
const index = validTypes.indexOf(r.type);
if (index !== -1) validTypes.splice(index, 1);
})
if (validTypes.length) return `${validTypes.join(', ')} is missing`;
return true;
};
So if you would have something like:
const test = {
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "X2"
}
],
"success": true
}
and you call check(test) it will return "X is missing". If all three types are present in the object that gets passed into the check function, it will return true. Of course this can be adjusted as you need. More objects, different types etc...
The JSON provided is kind of unstructured and doesn't meet many of my
requirements. I have tried this many ways but does take a very long time
when I provide 100,000 records
Implemented Code
for (var f in stack.data) {
var field = new Object();
for (var o in stack.data[f]['field_values']) {
field[stack.data[f]['field_values'][o]['field_name']] = stack.data[f]['field_values'][o]['value'];
}
stack.data[f]['field_values'] = field;
}
console.log(JSON.stringify(stack, null, 2));
Input JSON:
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
Expected Output:
{
"data": [
{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": {
"Newsletter?": true,
"Parent": "Gigi Hallow",
"Birthday": "2018-04-29",
"Related": "2012-00121-Sass",
"Referral": "Don Ho",
"Spouse": "Wo Fat"
}
Sometimes "field_values can be empty. Need to check them as well
{
"id": 950821118875,
"name": "www.google.com",
"field_values": [],
}
This is mostly re-arranging the values. Here values becomes keys. There should actually be one liner to handle this, but i am run out of options.
Hope the question is clear
It would probably help to declare a variable to hold the array element, rather than doing 4 levels of indexing every time through the loop. You can also use destructuring to extract the properties of the object.
And use {} rather than new Object.
Even if this doesn't improve performance, it makes the code easier to read.
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
for (var f in stack.data) {
const field = {};
const fobj = stack.data[f];
for (var o in fobj.field_values) {
const {field_name, value} = fobj.field_values[o];
field[field_name] = value;
}
fobj.field_values = field;
}
console.log(JSON.stringify(stack, null, 2));
I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);