Iterarting over array of objects and get unique values of each object - javascript

I have this variable inside data():
jsonStatham: {
"uniqueOne": {
"field1": "",
"field2": "",
"field3": "",
"field4": "",
"field5": "",
"freeTextArea": ""
},
"uniqueTwo": {
"field1": "",
"field2": "",
"field3":"",
"field4":"",
"field5":"",
"freeTextArea":""
},
"uniqueThree": {
"field1": "",
"field2": "",
"freeTextArea": ""
}
},
What I want is to check if a value from this input field:
<input type="text" name="platform" placeholder="Platform" id="platform" v-model="platform" required/>
is matching one of the keys of "jsonStatham" (uniqueOne/Two/Three) and then push the keys of the matching key into an array. so if the input === uniqueOne, so this array:
inputFields: [
],
Will look like this: inputFields["field1","field2","field3","field4","field5"]
That's what I tried:
appendFields() {
for (const [key, value] of Object.entries(this.jsonStatham)) {
if(this.brand === this.jsonStatham[key]){
//console.log("Brand =>", this.brand)
}
//console.log(`${key}: ${value}`);
this.inputFields.push({
[key]:value
})
}
//console.log("ALL input Fields: \n",this.inputFields)
},
What I get in inputFields is "uniqueOne","uniqueTwo","uniqueThree"

if (this.jsonStatham.hasOwnProperty(this.brand)) {
this.inputFields.push(...Object.keys(this.jsonStatham[this.brand]));
}

this should do the trick:
Condition:
if(Object.keys(this.jsonStatham).includes(this.brand) )
this will be True array ["uniqueOne","uniqueTwo","uniqueThree", ..etc] will include this.brand
Pushing to array:
this.inputFields.push(...Object.keys(value))

Related

Remove array of object if object inside is empty

I am preparing an array like this
datas[5] = { "qty_sized": "1", "resolution": "5", "status": "", "order": 1342 };
where [5] is dynamic from response.
I have and object mydata and inside that I have a object items.
I push array to object items, with assign
Object.assign(mydatadata.items, datas);
Now mydata.items has an array set,
`
items{
1 {qty_auth: "", resolution: "4", status: "", order: "1495"},
5 {qty_sized: "1", resolution: "4", status: "", order: "1485"}
}`
Now if qty_auth: "" , from which i need to check if qty_ is empty then remove the array . So expected output is something like this:
Note: qty_ is dynamic here.
items{ 5 {qty_sized: "1", resolution: "4", status: "", order: "1485"} }
and i want to result inside same object mydata.items
I tried something like this
const mydatadata.items = mydata.items.filter((o) =>
Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);
console.log(result);
but its now giving me any output
Using Object#entries, get the key-value pairs of items
Using Array#filter, iterate over the above array
In each iteration, check if the current item has a key starting with qty_ whose value is not empty. You can do this using Object#keys, Array#some, and String#startsWith.
Using Object#fromEntries, convert the filtered pairs to an object again.
const obj = {
items: {
1: {qty_auth: "", resolution: "4", status: "", order: "1495"},
5: {qty_sized: "1", resolution: "4", status: "", order: "1485"}
}
};
obj.items = Object.fromEntries(
Object.entries(obj.items)
.filter(([_, item]) =>
Object.keys(item).some(key => key.startsWith('qty_') && item[key])
)
);
console.log(obj);
You're talking about an array, but using curly brackets instead of square brackets. For filter() to work it would have to look like:
mydata = {
items: [
{qty_auth: "", resolution: "4", status: "", order: "1495"},
{qty_sized: "1", resolution: "4", status: "", order: "1485"}
]
}
Assuming it is an actual array there's still a problem with "const mydatadata.items", or at least it throws an error for me because mydatadata is not initialized. Unless it's a typo and it should be mydata, but then you'd be redeclaring it. So depending on what you want:
mydata.items = mydata.items.filter((o) =>
Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);
or
let mydatadata = {};
mydatadata.items = mydata.items.filter((o) =>
Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);
Furthermore you're storing the result in mydatadata but you're logging the variable result.
So depending on the previous answer:
console.log(mydatadata);
or
console.log(mydata);
Here's a fiddle: https://jsfiddle.net/b57qa82d/
You should probably just be using an array rather than an object. It's not really clear from your question what structure you need as you keep changing the terminology to describe your data. For example: "Now mydata.items has an array set" but your code says that it should be object with keys, not an array.
So I suggest: get your data in an array, and filter it by iterating over each object's entries and checking to see if any of the keys starting with "qty" has a value that isn't an empty string. You can then assign that filtered array to myObject.items.
const data = [
{ "qty_sized": "0", "resolution": "5", "status": "", "order": 2 },
{ "qty_auth": "", "resolution": "5", "status": "", "order": 3 },
{ "qty_auth": "1", "resolution": "5", "status": "", "order": 1342 },
{ "qty_sized": "", "resolution": "2", "status": "", "order": 1 },
{ "qty_sized": "1", "resolution": "1", "status": "", "order": 142 }];
const filtered = data.filter(obj => {
return Object.entries(obj).find(([key, value]) => {
return key.startsWith('qty') && value;
});
});
const myObject = { items: filtered };
console.log(myObject);
Additional documentation
Object.entries
find

Filter array of nested object using javascript

I want to filter specific object using nested object element this
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
This my data:
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
{
name: "df ",
token: null,
user_id: "e0efe9810ca289ccd590bce48051",
zipcode: "",
},
{
name: "Io",
phone: "88888888",
state: "NY",
token: null,
user_id: "c88ce38d0c86f786c3a4b0f9f967",
zipcode: "13201",
},
];
Expected output is:
Data array inside the first object of token using filter object. Below given expected out.
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
];
If you want a specific object, you could use find instead of filter. find will return the first element which verifies the condition specified to the find method where as the filter method is used to filters all the elements and returns all the element that matches the condition withing an array.
*You need to add the optional chaining ?. because the token object might be null like you have in some of your data
here both examples:
const data = [
{
"name": "test",
"token": {
"expiryTime": "2021-09-24T12:27:30.654Z",
"purpose": "ForgotPassword3",
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
},
"user_id": "acaacc940c9ebfe798dee68acf5c",
"zipcode": ""
},
{
"name": "df ",
"token": null,
"user_id": "e0efe9810ca289ccd590bce48051",
"zipcode": ""
},
{
"name": "Io",
"phone": "88888888",
"state": "NY",
"token": null,
"user_id": "c88ce38d0c86f786c3a4b0f9f967",
"zipcode": "13201"
}
]
const resFilter = data.filter(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resFilter);
const resObj = data.find(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resObj);
You must use the following code
const finded = data.filter(user => user?.token?.token ==="value"})
console.log(finded);

JQuery: Iterate over JSON File [duplicate]

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 1 year ago.
I'm having trouble to iterate over JSON file and get his parameters, this is an example of JSON file i created:
{
"One": { "Username": "", "Password": "", "unique3": "", "unique4": "", "unique5": "", "freeTextArea": "" },
"Two": { "Username": "", "Password": "", "SecretKey":"", "Autologinurl":"", "CrmUid":"", "freeTextArea":"" },
"Three": { "Username": "", "Password": "", "freeTextArea": "" }
}
I have this HTML input attribute:
<input type="text" name="platform" placeholder="Platform" id="platform"/>
What I want is to check if the Input is matching "one"/"two"/"three" from the JSON, and then create new input elements using DOM based on the parameters "one"/"two"/"three" have.
This is how I'm getting the JSON data using AJAX:
var platformJson = $.getJSON("platform.json");
How can I iterate correctly over this JSON file?
Get value of #platform input using .val()
Search for this value in data object and get the target
If the latter exists, iterate over it using $.each and append a new input to #platformForm using .append
const data = {
"One": { "Username": "1", "Password": "1", "AffiliateID": "1", "GI": "1", "CI": "1", "freeTextArea": "1" },
"Two": { "Username": "2", "Password": "2", "SecretKey":"2", "Autologinurl":"2", "CrmUid":"2", "freeTextArea":"2" },
"Three": { "Username": "3", "Password": "3", "freeTextArea": "3" }
};
const platform = $('#platform').val();
const props = data[platform];
if (props) {
$.each(props, function(prop, value) {
$('#platformForm').append(
`<input id="${prop}" value="${value}" />`
);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="platformForm">
<input type="text" name="platform" placeholder="Platform" id="platform" value="One"/>
</form>
You could try
$.getJSON('https://jsonplaceholder.typicode.com/todos/1', function (data) {
$.each(data, function (key, val) {
console.log(key);
});
});
Basically you need to provide a callback to the getJSON() method, which will be run with the JSON that you got back.
Then you should iterate via $.each() which will restructure and give you the key and value of the JSON.
Then you could manipulate and do what you need to do.
You don't need to "iterate" access the value from a JavaScript object by key. You can do the following:
const response = {
"One": {
"Username": "one",
"Password": "",
"AffiliateID": "",
"GI": "",
"CI": "",
"freeTextArea": ""
},
"Two": {
"Username": "",
"Password": "",
"SecretKey": "",
"Autologinurl": "",
"CrmUid": "",
"freeTextArea": "",
},
"Three": {
"Username": "",
"Password": "",
"freeTextArea": ""
}
}
const inputValue = $('#platform').val();
const keys = Object.keys(response);
console.log(keys.includes(inputValue));
const obj = response[inputValue];
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="platform" placeholder="Platform" id="platform" value="One" />
I recommend using lowerCase keys for your JSON, so that it'll be easier for you to match throughout the application.

create array from json

I'm receiving this JSON below
{
"category": "test",
"sealing_temp_1": "",
"sealing_temp_2": "",
"sealing_temp_3": "",
"level_sensor_1": "",
"level_sensor_2": "",
"level_sensor_3": "",
"check_pack_1": "",
"check_pack_2": "",
"check_pack_3": "",
"comment": ""
}
and I would like to turn it to this structure and save
{
"category": "test",
"sealing_temp": "['a', 'b', 'c']",
"level_sensor": "['x', 'y', 'z']",
"check_pack": "[1, 2, 3]",
"comment": ""
}
Can someone guide me, I tried to use a for..in but got lost in the process
You could split the key and if it has digits at the end in it, then use it for an array to fill.
This proposal change the object and deletes unwanted properties which values are now in an array collected.
var object = { category: "test", sealing_temp_1: "s1", sealing_temp_2: "s2", sealing_temp_3: "s3", level_sensor_1: "l1", level_sensor_2: "l2", level_sensor_3: "l3", check_pack_1: "c1", check_pack_2: "c2", check_pack_3: "c3", comment: "cc" };
Object.keys(object).forEach(function (k) {
var parts = k.split(/_(?=\d+$)/);
if (parts.length === 2) {
object[parts[0]] = object[parts[0]] || [];
object[parts[0]][parts[1] - 1] = object[k]; // subtract one for zero based array
delete object[k];
}
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Iterate through the child objects and get all the values with javascript

var formmd = {
"frmType": "Registration",
"frmStage": "step1-complete",
"formattr": {
"SystemUser": {
"LoginName": "A#test.com",
"Password": "password",
"PIN": "",
"IsTestUser": false
},
"ConsumerAddress": {
"AddressLine1": "201 MOUNT Road",
"AddressLine2": null,
"AddressTypeId": "1",
"City": "OLA TRAP",
"State": "NM",
"Zipcode": "60005"
},
"ConsumerPhone": {
"PhoneTypeId": 6,
"PhoneNumber": "9876543210",
"PrimaryPhoneIndicator": null,
"AllowVoicemail": false
},
"PhysicianSpecialty": {
"SpecialtyList": [
"1",
"2"
]
},
}
}
I'm trying to fetch all the values of the child objects under formattr but I'm unable to iterate inside the child objects. The following is the script I tried.
My Result should be
"A#test.com"
"password"
"PIN": ""
False
201 MOUNT Road"
The script I tried is
function walk(formmd) {
var obj1 = formmd.formattr;
for(var key in obj1){
if (obj1.hasOwnProperty(key)) {
var val1 = obj1[key];
if(val1.hasOwnProperty(key)){
for(var key in val1){
var val2 =val1[key];
console.log("val2");
}
}
}
}
}
How to access the keys of child objects in an automated way?
Try like this
for (var key in formmd) {
var val1 = formmd[key];
if (key=="formattr") {
for (var key1 in val1) {
var val2 = val1[key1];
for(var key2 in val2)
console.log(val2[key2]);
}
}
}
DEMO
You might find it easier to understand code written in a functional style. This is one solution, which I'll explain:
Object.values(formmd.formattr)
.map(obj => Object.values(obj))
.reduce((acc, vals) => acc.concat(vals), [])
The first expression Object.values(formmd.formattr) gives you an array of all the values (not keys) under formmd.formattr. Something like:
[{"LoginName": "A#test.com", "Password": "password", …}, {"AddressLine1": "201 MOUNT Road", "AddressLine2": null, …}, …]
Since you want the values within each of these sub-objects the next line .map(obj => Object.values(obj)) will do just that. It returns a new array where each object in the input array is transformed through Object.values(…). It returns something like:
[["A#test.com", "password", "", false], ["201 MOUNT Road", null, "1", …], …]
This array has all the data you're after, but in nested arrays, so it needs to be flattened with .reduce((acc, vals) => acc.concat(vals), []). This reduce will successively concat these sub-arrays to produce a single array like:
["A#test.com", "password", "", false, "201 MOUNT Road", null, "1", …]
which contains all the values of the child objects under formattr.
Here's some other ways to do it:
Object.values(formmd.formattr)
.reduce((acc, x) => acc.concat(Object.values(x)), [])
or
[].concat(...
Object.values(formmd.formattr)
.map(obj => Object.values(obj)))
You will have to use Object.entries()
The Object.entries() method returns an array of a given object's own
enumerable string-keyed property [key, value] pairs, in the same order
as that provided by a for...in loop. (The only important difference is
that a for...in loop enumerates properties in the prototype chain as
well).
Example -
for (const [key, value] of Object.entries(objectName)) {
console.log(`${key}: ${value}`);
}
Code Snippet -
var formmd = {
"frmType": "Registration",
"frmStage": "step1-complete",
"formattr": {
"SystemUser": {
"LoginName": "A#test.com",
"Password": "password",
"PIN": "",
"IsTestUser": false
},
"ConsumerAddress": {
"AddressLine1": "201 MOUNT Road",
"AddressLine2": null,
"AddressTypeId": "1",
"City": "OLA TRAP",
"State": "NM",
"Zipcode": "60005"
},
"ConsumerPhone": {
"PhoneTypeId": 6,
"PhoneNumber": "9876543210",
"PrimaryPhoneIndicator": null,
"AllowVoicemail": false
},
"PhysicianSpecialty": {
"SpecialtyList": [
"1",
"2"
]
},
}
}
for (const [key, value] of Object.entries(formmd.formattr)) {
console.log('Value',value);
}

Categories

Resources