I have an array like this :
[
{
"title": "name",
"value": ""
},
{
"title": "version",
"value": ""
},
{
"title": "inventory_name",
"value": ""
},
{
"title": "inventory_version",
"value": ""
},
{
"title": "differed",
"value": ""
},
{
"title": "differed_name",
"value": ""
},
{
"title": "accept_error_while_reboot",
"value": ""
},
{
"title": "setup_check",
"value": ""
},
{
"title": "setup_install",
"value": ""
},
{
"title": "setup_install_partial",
"value": ""
},
{
"title": "params_install",
"value": ""
},
{
"title": "params_install_partial",
"value": ""
},
{
"title": "results_install_ok",
"value": ""
},
{
"title": "results_install_reboot_defered",
"value": ""
},
{
"title": "results_install_reboot_immediate",
"value": ""
},
{
"title": "results_install_partial_ok",
"value": ""
},
{
"title": "results_install_partial_reboot_defered",
"value": ""
},
{
"title": "results_install_partial_reboot_immediate",
"value": ""
}
];
Is it possible to make subarrays that contains the same title field string ?
For example in this case , I will have :
array1 = [
{
"title": "differed",
"value": ""
},
{
"title": "differed_name",
"value": ""
}
]
array2 = [
{
"title": "setup_check",
"value": ""
},
{
"title": "setup_install",
"value": ""
},
{
"title": "setup_install_partial",
"value": ""
}
]
and so on...
In case of single elements , I should have :
[
{
"title": "name",
"value": ""
}
]
I'm searching for a generic approach.
I know I can use, for example, indexOf('results') with filter function, however I'd like if it's possible to avoid the hardcode since it's not always the same titles.
Any ideas ?
Fiddle
You can use an object to group similar items:
var groups = {};
parameter_list.forEach(function(p){
var key = p.title.split('_')[0];
if(!groups[key]) {
groups[key] = [];
}
groups[key].push(p);
});
Working demo:
http://jsfiddle.net/t459o6v1/3/
Group the data with .reduce()
var groups = data.reduce(function(result, currentValue) {
var key = currentValue.title.split("_")[0];
if (typeof result[key] === "undefined") {
result[key] = [];
}
result[key].push(currentValue);
return result;
}, {});
And then (if needed) use .map() to transform the object into "subarrays"
var subArrays = Object.keys(groups).map(function(key) {
return groups[key];
});
var data = [{
"title": "name",
"value": ""
}, {
"title": "version",
"value": ""
}, {
"title": "inventory_name",
"value": ""
}, {
"title": "inventory_version",
"value": ""
}, {
"title": "differed",
"value": ""
}, {
"title": "differed_name",
"value": ""
}, {
"title": "accept_error_while_reboot",
"value": ""
}, {
"title": "setup_check",
"value": ""
}, {
"title": "setup_install",
"value": ""
}, {
"title": "setup_install_partial",
"value": ""
}, {
"title": "params_install",
"value": ""
}, {
"title": "params_install_partial",
"value": ""
}, {
"title": "results_install_ok",
"value": ""
}, {
"title": "results_install_reboot_defered",
"value": ""
}, {
"title": "results_install_reboot_immediate",
"value": ""
}, {
"title": "results_install_partial_ok",
"value": ""
}, {
"title": "results_install_partial_reboot_defered",
"value": ""
}, {
"title": "results_install_partial_reboot_immediate",
"value": ""
}];
var groups = data.reduce(function(result, currentValue) {
var key = currentValue.title.split("_")[0];
if (typeof result[key] === "undefined") {
result[key] = [];
}
result[key].push(currentValue);
return result;
}, {});
var subArrays = Object.keys(groups).map(function(key) {
return groups[key];
});
console.log(JSON.stringify(subArrays));
I came up with a solution using Immutable.JS, but you could probably do something similar with lodash or underscore. Note that this is a functional version, not imperative.
First create a function that gets the prefix:
function getPrefix(name) {
var substr = name.substring(0, name.indexOf('_'))
return substr ? substr : name;
}
Then use the groupBy function:
Immutable.fromJS(arr).groupBy(element => getPrefix( element['title']))
.toJS();
This will give you an array of arrays with the title as it's key.
Related
I Have Two Array, One is normal one where dates values are being stored
var = [
"2022-05-01",
"2022-05-02",
"2022-05-03",
"2022-05-04",
"2022-05-05",
"2022-05-06",
"2022-05-07",
"2022-05-08",
"2022-05-09",
"2022-05-10",
"2022-05-11",
"2022-05-12",
"2022-05-13",
"2022-05-14",
"2022-05-15",
"2022-05-16",
"2022-05-17",
"2022-05-18",
"2022-05-19",
"2022-05-20",
"2022-05-21",
"2022-05-22",
"2022-05-23",
"2022-05-24",
"2022-05-25",
"2022-05-26",
"2022-05-27",
"2022-05-28",
"2022-05-29",
"2022-05-30"
]
The other one is objects of Array where two objects are present
var b = [
{
"k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
"v_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
"key": "Testing",
"value": "999",
"start_date": "2022-05-06T00:00:00.000Z",
"end_date": "2022-05-06T00:00:00.000Z"
},
{
"k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
"v_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
"key": "Testing",
"value": "189",
"start_date": "2022-05-08T00:00:00.000Z",
"end_date": "2022-05-`enter code here`08T00:00:00.000Z"
}
]
My Requirement is to Convert new array into like this
[
{
"value": "",
"value_id": "",
"date": "2022-05-01"
},
{
"value": "",
"value_id": "",
"date": "2022-05-02"
},
{
"value": "",
"value_id": "",
"date": "2022-05-03"
},
{
"value": "",
"value_id": "",
"date": "2022-05-04"
},
{
"value": "",
"value_id": "",
"date": "2022-05-05"
},
{
"value": "999",
"value_id": "48138929-6848-4ffe-86ce-183c75d021b4",
"date": "2022-05-06"
},
{
"value": "",
"value_id": "",
"date": "2022-05-07"
},
{
"value": "189",
"value_id": "06c4f66f-efae-4981-bebd-6734addab4a5",
"date": "2022-05-08"
},
{
"value": "",
"value_id": "",
"date": "2022-05-09"
},
{
"value": "",
"value_id": "",
"date": "2022-05-10"
},
{
"value": "",
"value_id": "",
"date": "2022-05-11"
}
]
Like in the object 2022-06-11 data is there, so the new array will consist an object which will have properties related to that object. Similar to if the object has start_date present which is also in date array, so the new array will consist object for those info. Otherwise it will create blank object respective to date.
But I am able to come with this
[
{
"value": "999",
"value_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
"date": "2022-05-06"
},
{
"value": "189",
"value_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
"date": "2022-05-08"
},
{
"value": "",
"date": "2022-05-03"
},
{
"value": "",
"date": "2022-05-04"
},
{
"value": "",
"date": "2022-05-05"
},
{
"value": "",
"date": "2022-05-06"
},
{
"value": "",
"date": "2022-05-07"
},
{
"value": "",
"date": "2022-05-08"
},
{
"value": "",
"date": "2022-05-09"
},
{
"value": "",
"date": "2022-05-10"
},
{
"value": "",
"date": "2022-05-11"
},
{
"value": "",
"date": "2022-05-12"
},
{
"value": "",
"date": "2022-05-13"
},
{
"value": "",
"date": "2022-05-14"
},
{
"value": "",
"date": "2022-05-15"
},
{
"value": "",
"date": "2022-05-16"
},
{
"value": "",
"date": "2022-05-17"
},
{
"value": "",
"date": "2022-05-18"
},
{
"value": "",
"date": "2022-05-19"
},
{
"value": "",
"date": "2022-05-20"
},
{
"value": "",
"date": "2022-05-21"
},
{
"value": "",
"date": "2022-05-22"
},
{
"value": "",
"date": "2022-05-23"
},
{
"value": "",
"date": "2022-05-24"
},
{
"value": "",
"date": "2022-05-25"
},
{
"value": "",
"date": "2022-05-26"
},
{
"value": "",
"date": "2022-05-27"
},
{
"value": "",
"date": "2022-05-28"
},
{
"value": "",
"date": "2022-05-29"
},
{
"value": "",
"date": "2022-05-30"
}
]
It is taking only first entry and printing and rest are coming as blank.
My Code: -
var a = {};
dateArr = [];
for (var j = 0; j < this.date_val.length; j++) {
debugger;
var b = {}
console.log(val2.value[j]);
if (val2.value.length > 0) {
const newKey = this.date_val[j];
b[newKey] = val1.data;
// if (
// moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
// this.date_val[j]
// ) {
// this.vala = val2.value[j].value;
// this.valb = val2.value[j].val_id;
// this.valc = moment(val2.value[j].start_date).format(
// "YYYY-MM-DD"
// );
// }
// if (
// moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
// this.date_val[j]
// ) {
a = {
value:
val2.value[j] != undefined ? val2.value[j].value : "",
value_id:
val2.value[j] != undefined
? val2.value[j].v_id
: undefined,
date:
val2.value[j] != undefined
? moment(val2.value[j].start_date).format(
"YYYY-MM-DD"
)
: this.date_val[j],
};
// }
} else {
a = {
value: "",
value_id: undefined,
date: this.date_val[j],
};
}
dateArr.push(a);
}
this.nameArray.push({
key: val1.key,
key_val: val1.id,
date: dateArr,
});
Can someone please help me with this? Thanks in Advance.
var a = [
"2022-05-01",
"2022-05-02",
"2022-05-03",
"2022-05-04",
"2022-05-05",
"2022-05-06",
"2022-05-07",
"2022-05-08",
"2022-05-09",
"2022-05-10",
"2022-05-11",
"2022-05-12",
"2022-05-13",
"2022-05-14",
"2022-05-15",
"2022-05-16",
"2022-05-17",
"2022-05-18",
"2022-05-19",
"2022-05-20",
"2022-05-21",
"2022-05-22",
"2022-05-23",
"2022-05-24",
"2022-05-25",
"2022-05-26",
"2022-05-27",
"2022-05-28",
"2022-05-29",
"2022-05-30",
];
var b = [
{
k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
v_id: "aacc1765-a1d3-43c3-8233-beae19d258e5",
key: "Testing",
value: "999",
start_date: "2022-05-06T00:00:00.000Z",
end_date: "2022-05-06T00:00:00.000Z",
},
{
k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
v_id: "ad95cc4a-ec72-4d6e-a452-f519358f265d",
key: "Testing",
value: "189",
start_date: "2022-05-08T00:00:00.000Z",
end_date: "2022-05-08T00:00:00.000Z",
},
];
let results = a.map((dateString, idx) => {
// You'll want to parse the time, many ways
// to do this, then compare times. This is
// hardcoded to work for this exact format
let bWithMatchedIndices = b.find(
({ start_date }) => dateString === start_date.split("T")[0]
);
if (bWithMatchedIndices?.start_date.split("T")[0] === dateString) {
return {
date: dateString,
value: bWithMatchedIndices.value,
value_id: bWithMatchedIndices.v_id,
};
} else {
return {
date: dateString,
value: "",
value_id: "",
};
}
});
console.log(results);
Just loop over the dates in A and find a match in B. Then create an object with the members you need and push it to the resulting array.
interface NewItem {
date: string,
value: string,
value_id: string
}
function transform(a: any[], b: any[]): NewItem[] {
let newArray: NewItem[] = []
a.forEach(item => {
const objectFound = b.find(x => x.start_date.split('T')[0] === item)
if (objectFound) {
newArray.push({ date: item, value: objectFound.value, value_id: objectFound.v_id })
} else {
newArray.push({ date: item, value: '', value_id: '' })
}
})
return newArray
}
console.log(transform(a, b))
You might want to create interfaces for the two original objects too, but I think this should help you on your way just fine.
Here's the result in a Playground.
This question already has answers here:
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed last year.
I have a data like this:
{
"countries": {
"US": {
"details": {
"code": 1,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
},
"UK": {
"details": {
"code": 44,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
}
}
}
I want to loop through it and extract people so I can loop through the people and display them on the site.
var countries = {
"countries": {
"US": {
"details": {
"code": 1,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
},
"UK": {
"details": {
"code": 44,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
}
}
}
for (let [key, value] of Object.entries(countries.countries)) {
//console.log(value);
for (var people in value.people) {
console.log(people);
}
}
But I keep getting 0, 1, how can I get the value of people array?
For array (and other data structures implementing the iterable interface) it's for...of, not for...in (which is for iterating over keys of an object).
var countries = {
"countries": {
"US": {
"details": {
"code": 1,
"population": ""
},
"people": [{
"name": ""
},
{
"name": ""
}
]
},
"UK": {
"details": {
"code": 44,
"population": ""
},
"people": [{
"name": ""
},
{
"name": ""
}
]
}
}
}
for (let [key, value] of Object.entries(countries.countries)) {
for (let people of value.people) {
console.log(people);
}
}
const obj = {
"countries": {
"US": {
"details": {
"code": 1,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
},
"UK": {
"details": {
"code": 44,
"population": ""
},
"people": [
{
"name": ""
},
{
"name": ""
}
]
}
}
}
for (let key in obj.countries) {
console.log(obj.countries[key].people);
}
I have below this nested object
I need to create an array using this object containing keys. And if keys are object then it should use .dot syntax. and if it is an array then it should give me key.0.keyName. Is it possible to do so?
Output
[
"AllowIPNPayment",
"AllowOnlinePayment",
"MetaData.CreateTime",
"MetaData.LastUpdatedTime",
"CustomField.0.DefinitionId",
"CustomField.0.Name",
"CustomField.0.Type",
...
]
What I have tried is just ugly and does give me expected result. If it is possible with more concise way.
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
let object = {}
for (let k in invoiceObject) {
if (typeof invoiceObject[k] === "object") {
object[k] = {};
for (let l in invoiceObject[k]) {
object[k][l] = "";
}
} else if (typeof invoiceObject[k] === "array") {
object[k] = [];
for (let l in invoiceObject[k][0]) {
object[k][l] = "";
}
} else {
object[k] = "";
}
}
console.log(object)
You can create a recursive function (getSchema) that checks if a value (val) is an object (arrays included), iterate it with _.flatMap(), and collects the keys until it hits a value which is not an object. It then joins the collected keys and returns the string.
const getSchema = (val, keys = []) =>
_.isObject(val) ? // if it's an object or array
_.flatMap(val, (v, k) => getSchema(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
keys.join('.') // return the joined keys
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
const result = getSchema(invoiceObject)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Without lodash, the main change is to use Object.entries() to get an array of [key, value] pairs, since Array.flatMap() can't iterate objects:
const getSchema = (val, keys = []) =>
typeof val === 'object' && val !== null ? // if it's an object or array
Object.entries(val) // get [key, value] pairs of object/array
.flatMap(([k, v]) => getSchema(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
keys.join('.') // return the joined keys
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
const result = getSchema(invoiceObject)
console.log(result)
inspired by the answer given in this post and understanding you just want to get the property-names, not values, you could do it like this. sorry, this uses plain javascript.
function flattenObjectToKeyArray(ob) {
var toReturn = [];
for (var prop in ob) {
if (!ob.hasOwnProperty(prop)) continue;
if ((typeof ob[prop]) == 'object' && ob[prop] !== null) {
var flatObject = flattenObjectToKeyArray(ob[prop]);
for (var idx = 0; idx < flatObject.length; idx++) {
toReturn.push(prop + '.' + flatObject[idx]);
}
} else {
toReturn.push(prop);
}
}
return toReturn;
}
You could solve this with a recursive function. The function below keeps track of the current keys, and joins them as soon as an end point is reached (a non-object or empty object/array).
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 };
function getDotKeys(item, keys = []) {
const isObject = item && typeof item == "object";
if (!isObject) return Array.of(keys.join("."));
const pairs = Array.isArray(item)
? item.map((value, index) => [index, value])
: Object.entries(item);
const isEmpty = !pairs.length;
if (isEmpty) return Array.of(keys.join("."));
const result = [];
for (const [key, value] of pairs) {
const dotKeys = getDotKeys(value, [...keys, key]);
result.push(...dotKeys);
}
return result;
}
console.log(getDotKeys(invoiceObject));
This does produce a different result than what you have in your question, since your solution stops at the second level for objects and third level for arrays. This solution also includes more then only index 0.
I am saving data in localstorage temporary, because of user have to go to another page before submit the form, But i have problem to display data in form again.
Here is my code
$('#ip_range').click(function(e) {
var data = $('#Demoform').serializeArray();
// localStorage.setItem('formData', JSON.stringify(data));
var formData = JSON.parse(localStorage.getItem('formData'));
$.each(formData, function(i, val) {
var data = $("input[name='"+val.name+"']").val(val.value);
console.log(data);
});
});
This is the json data that i want to display
[{
"name": "timezone",
"value": "America/New_York"
}, {
"name": "fiscal_year",
"value": "1"
}, {
"name": "first_day",
"value": "0"
}, {
"name": "highest_level",
"value": "393"
}, {
"name": "company_administrator",
"value": "393"
}, {
"name": "ip_restrictions",
"value": "1"
}, {
"name": "ip_range",
"value": "4"
}, {
"name": "languages_enabled",
"value": "0"
}, {
"name": "language",
"value": ""
}, {
"name": "enable_single_sign",
"value": "0"
}, {
"name": "user_sign_off",
"value": "0"
}, {
"name": "widgets_sort_order",
"value": "Links,Training,Task"
}, {
"name": "confirm",
"value": "1"
}]
You are close here, but this part $("input[name='"+val.name+"']").val(val.value) is what I think your problem is. Try the code below. I think this is what you are trying to do.
I would structure the input like such: var data = $('<input name="'+ val.name +'" value="'+ val.value +'" />');
I'd put a stack snippet up, but it doesn't work well with localStorage, so click on the jsfiddle link and click the IP Range button to see the form get the inputs with the proper names.
Demo: https://jsfiddle.net/ygh8pdk1/
var data = [
{
"name": "timezone",
"value": "America/New_York"
}, {
"name": "fiscal_year",
"value": "1"
}, {
"name": "first_day",
"value": "0"
}, {
"name": "highest_level",
"value": "393"
}, {
"name": "company_administrator",
"value": "393"
}, {
"name": "ip_restrictions",
"value": "1"
}, {
"name": "ip_range",
"value": "4"
}, {
"name": "languages_enabled",
"value": "0"
}, {
"name": "language",
"value": ""
}, {
"name": "enable_single_sign",
"value": "0"
}, {
"name": "user_sign_off",
"value": "0"
}, {
"name": "widgets_sort_order",
"value": "Links,Training,Task"
}, {
"name": "confirm",
"value": "1"
}
];
localStorage.setItem('formData', JSON.stringify(data));
$('#ip_range').click(function(e) {
var formData = JSON.parse(localStorage.getItem('formData'));
$.each(formData, function(i, val) {
var data = $('<input name="'+ val.name + '" value="'+ val.value +'" />');
$('#form-data').append(data);
});
});
I am trying to transform my data from one format to another format , but I am getting error obj[i] is not iterable why I want to get expected output as shown below in variable
const data = {
"GENERAL": {
"value": null,
"type": "LABEL",
},
"Mobile NUMBER": {
"value": "04061511",
"type": "FIELD",
},
"Abc NUMBER": {
"value": "89999",
"type": "FIELD",
},
"Personal Info": {
"value": null,
"type": "LABEL",
},
"Address": {
"value": "g-78",
"type": "FIELD",
}, "local": {
"value": "090099",
"type": "FIELD",
}
}
const obj = {}
for (var i in data) {
const {type} = data[i];
if (type === 'LABEL') {
obj[i] = []
} else {
obj[i] = [...obj[i], data[i]]
}
}
console.log(obj)
const expectedout = {
"GENERAL": [{
"value": "04061511",
"type": "FIELD",
"displaytext": "Mobile NUMBER"
}, {
"value": "89999",
"type": "FIELD",
"displaytext": "Abc NUMBER"
}],
"Personal Info": [{
"value": "g-78",
"type": "FIELD",
"displaytext": "Address"
}, {
"value": "090099",
"type": "FIELD",
"displaytext": "local"
}]
}
Is there any better approach to transform my current data to expected data?I am ES6 in react
here is my code
https://jsbin.com/sesipuzeni/1/edit?html,js,console,output
Update
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
VM5628:8
it seems object property don't have guarantee.yes is correct when you have number and string
but when you have always "string" it comes in same order
var obj = {
"first":{a:"jjj"},
"yyy":{a:"jjqej"},
"ttt":{a:"jjsqj"},
"ggg":{a:"jjjs"},
"second":{a:"jjcj"}
};
for (var i in obj) { console.log(i); };
The problem is that when you're processing the next element of the original object, i is no longer the key of the element containing the array of values. You need to save that in another variable.
const data = {
"GENERAL": {
"value": null,
"type": "LABEL",
},
"Mobile NUMBER": {
"value": "04061511",
"type": "FIELD",
},
"Abc NUMBER": {
"value": "89999",
"type": "FIELD",
},
"Personal Info": {
"value": null,
"type": "LABEL",
},
"Address": {
"value": "g-78",
"type": "FIELD",
},
"local": {
"value": "090099",
"type": "FIELD",
}
}
const obj = {};
var lastLabel;
for (var i in data) {
if (data[i].type === 'LABEL') {
obj[i] = []
lastLabel = i;
} else {
data[i].displaytext = i;
obj[lastLabel] = [...obj[lastLabel], data[i]]
}
}
console.log(obj)
Note that this whole approach depends on object properties retaining their order, which isn't guaranteed in JavaScript. But it happens to work in most existing implementations, I think.