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']
Related
{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
This is list of arrays with keys and values as array, I want to return all the keys based on a particular value;
For Eg:
I want to return the parent keys which are [arr1,arr2], reason being both the arrays contain a value Unique, So I want to return the parent key of both the values, which is arr1 and arr2 respectively.
Note: The list can have n numbers of arrays.
Any help would be appreciated. Thanks in advance.
The simplest way to go about this is:
Loop through the keys in your object
Check if the array contains any objects with the name "Unique"
If so, add the objects key to an array
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
This is a more generic approach:
const getKeysByValue = (data, value) => {
const dataKeys = Object.keys(data);
const valueKey = Object.keys(value);
return dataKeys.filter(currKey => {
for(let element of data[currKey])
if(element[valueKey] === value[valueKey])
return true;
});
}
const data = {
"arr1":[
{
"name":"something1",
"shape": "Trapezium",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"shape": "Octagon",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"shape": "Square",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"shape": "Triangle",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"shape": "Circle",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"shape": "Triangle",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
}
],
"arr3":
[
{
"name":"Not-Unique",
"shape": "Circle",
"id":"8hcf14ee58ea25g343e9a2f208df215c"
}
]
}
console.log(getKeysByValue(data, {"name": "something2"})); // ["arr1"]
console.log(getKeysByValue(data, {"name": "Unique"})); // ["arr1", "arr2"]
console.log(getKeysByValue(data, {"shape": "Circle"})); // ["arr1", "arr3"]
console.log(getKeysByValue(data, {"shape": "Square"})); // ["arr1"]
The function receives two parameters, data and value. value is expected to be in the format of the value you are looking to filter with. In your example you wanted it to be "Unique" and in each object in the array it was presented like "name": "Unique" so we will send it as an object, {"name": "Unique"}.
In this way you can have different value to filter with. In the example above I added a shape key and value to each element, we can filter by this value too as shown in the example above.
you can do like this :
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
arr=[]
//loop over dict with pair keys and value
for (const [key, value] of Object.entries(obj)) {
//get the list of name from dict and check it if it contains Unique string
value.map(e=>e.name).includes("Unique") ? arr.push(key) : false
}
console.log(arr)
You can use array some method
const data = {
"arr1": [{
"name": "something1",
"id": "233111f4-9126-490d-a78b-1724009fa484"
},
{
"name": "something2",
"id": "50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name": "something4",
"id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name": "something5",
"id": "ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2": [{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
}]
}
var obj = [],
keys;
for (keys in data) {
data[keys].some(a => "Unique" === a.name) && obj.push(keys);
}
console.log(obj);
An alternative way that i could think of is using Regexp
var obj = {
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
let str = JSON.stringify(obj);
let match = str.matchAll(/\"([\w\d]+)\":\[(?:{[\s\S]+},)*{\"name\":\"Unique\"/g);
let parent = [];
for(let m of match){
parent.push(m[1]);
}
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 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" }
}
This is a nested json file and I am trying to arrange it in a readable format to display in a table
I tried to manually put all the keys and values with in a for loop but there should be an elegant way to achieve this and hence I am reaching SO.
The actual JSON is quite a nested one and needed time to execute data with 500k rows
The result should be enhanced JSON with parent values appearing for child values as well
var property = {
"data": [{
"ID": "123456",
"name": "Coleridge st",
"criteria": [
{
"type": "type1",
"name": "name1",
"value": "7",
"properties": []
},
{
"type": "type2",
"name": "name2",
"value": "6",
"properties": [
{
"type": "MAX",
"name": "one",
"value": "100"
}, {
"type": "MIN",
"name": "five",
"value": "5"
}
]
},
{
"type": "type3",
"name": "name3",
"value": "5",
"properties": [{
"type": "MAX1",
"name": "one6",
"value": "1006"
}, {
"type": "MIN2",
"name": "five6",
"value": "56"
}]
}
]
},
{
"ID": "456789",
"name": "New Jersy",
"criteria": [
{
"type": "type4",
"name": "name4",
"value": "6",
"properties": [{
"type": "MAX12",
"name": "one12",
"value": "10012"
}, {
"type": "MIN23",
"name": "five12",
"value": "532"
}]
}
]
}]
};
var output = [];
property.data.forEach(function (users) {
var multirows = {
id: users.ID,
name: users.name,
};
for (var i = 0; i < users.criteria.length; i++) {
var criterias = {
type: users.criteria[i].type,
name: users.criteria[i].name,
value: users.criteria[i].value,
}
var mat_contacts_rows;
if (!isEmpty(users.criteria[i].properties)) {
for (var j = 0; j < users.criteria[i].properties.length; j++) {
var property = {
type: users.criteria[i].properties[j].type,
name: users.criteria[i].properties[j].name,
value: users.criteria[i].properties[j].value
};
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
} else {
var property = [];
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
}
});
console.log(JSON.stringify(output, undefined, 2))
function isEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
I think this could be a great exercise to you to don't answer your question but to give you some tips. You should first look at : Lodash wish has a bunch of usefull method to help you doing what you'r trying to do.
In a second time you should avoir using .forEach or for loops and try using Array.prototype.map or Array.prototype.reduce
I have the following JSON object. Using JQuery I need to find the values of the following:
summary.nameValues.ID and detail.TypedNameValues.size
Could somebody please show how this can be achieved using JQuery?
[
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": [
"232639"
]
},
{
"Name": "City",
"Values": [
"London"
]
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
]
jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
Use like so:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
This answer taken from another thread. You may find more help here: use jQuery's find() on JSON object
Performing this kind of queries on JSON structures are trivial using DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which one can execute XPath expressive searches.
Check out this fiddle;
http://jsfiddle.net/hbi99/kLE2v/
The code can look like this:
var data = [
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": "232639"
},
{
"Name": "City",
"Values": "London"
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
],
res = JSON.search( data, '//*[Name="size"]' );
console.log( res[0].Value );
// 434353
Some one else as already answered, either way here is my version for the same.
<textarea id="ta" style="display:none;">[
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": [
"232639"
]
},
{
"Name": "City",
"Values": [
"London"
]
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
]</textarea>
Parser
var obj = $.parseJSON($('#ta').val());
var nameValues = obj[0].summary.NameValues;
var typedNameValues = obj[0].detail.TypedNameValues;
function getObjByName(o, name) {
for (var i = 0; i < o.length; i++) {
if (o[i].Name == name) {
return o[i];
}
}
return null;
}
alert(getObjByName(nameValues, 'Id').Values.join(", "));
alert(getObjByName(typedNameValues, 'size').Value);
A working fiddle for you on the same.
http://jsfiddle.net/3EVE4/