JavaScript / typescript: unable to regenerate object - javascript

I have an object as specified below:
{
"player settings": [
{
"id": 1,
"labelName": "site language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "2"
},
{
"id": 2,
"labelName": "subtitle language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "1"
},
]
},
{
"channel": [
{
"id": 11,
"labelName": "channel label",
"dataType": "TX",
"selectedData": "jhfh"
}
]
},
{
"others": [
{
"id": 16,
"labelName": "others label",
"dataType": "TX",
"selectedData": "dhgdhg"
}
]
}
How can I modify and re-generate the object with the following conditions:
if dataType === 'DD' then convert selectedData into number.
I wrote the below code but stuck here:
for (var j = 0; j < this.myobject.length; j++){
this.myobject.forEach(obj => {
console.log(obj)
});
}

You can use for..in
let data = {"player settings": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "DD","selectedData": "2"},],"player settings2": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "NO DD","selectedData": "2"},]}
for (let key in data) {
data[key].forEach(obj => {
if (obj.dataType === "DD") {
obj.selectedData = +(obj.selectedData || 0)
}
})
}
console.log(data)
Immutable approach
let data = {"player settings": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "DD","selectedData": "2"},],"player settings2": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "NO DD","selectedData": "2"},]}
let newObj = {}
for (let key in data) {
newObj[key] = data[key]
data[key].forEach(obj => {
if (obj.dataType === "DD") {
newObj.selectedData = +(obj.selectedData || 0)
}
})
}
console.log(newObj)

We can use filter on the main obj and then proceed modifying the object.
function modifyDataToNumber(){
let myObject = jsonObj['player settings'];
let ddMyObject = myObject.filter((row)=>(row["dataType"]==="DD"));
console.log(ddMyObject[0]["selectedData"]);
ddMyObject.forEach((row,index)=>{
ddMyObject[index]["selectedData"] = +ddMyObject[index]["selectedData"];
})
console.log(jsonObj);
}
modifyDataToNumber();

I would do something like this
const json = {
"player settings": [
{
"id": 1,
"labelName": "site language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "2"
},
]
};
json['player settings'] = json['player settings'].map(setting => {
if (setting.dataType === 'DD') {
const updatedSetting = {
...setting,
selectedData: parseInt(setting.selectedData)
};
return updatedSetting;
}
return setting;
});
console.log('Result', json);

Since you say "re-generate", I assume you want an immutable approach to this (that is, generate a copy of the data with the desired changes, rather than changing the original object).
To that, you can use spread syntax and Array#map:
let convertSetting = setting => ({
...setting,
selectedData: setting.dataType === "DD"
? parseInt(setting.selectedData)
: setting.selectedData
});
let convert = x => ({
...x,
["player settings"]: x["player settings"].map(convertSetting)
});
Then you can use that function as convert(yourOriginalObject).

Related

Flatten an object using lodash

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.

How to replace an array of objects with an array including newer objects in TypeScript?

For example: I have an array of objects like this:
let arrayOfObjects: [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
Now I want to replace or overwrite the array above with the same array, but including different values (same keys, different values):
let arrayOfObjects: [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
];
How can this be done in TypeScript?
Try this JS
let oneArray = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
let twoArray = [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
];
let newArray = Object.assign([], oneArray, twoArray);
console.log(newArray);
In TS
interface Data {
oneArray: array;
twoArray: array;
}
function merge(data: Data) {
return Object.assign([], data.oneArray, data.twoArray);
}
let user = {
oneArray: [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
],
twoArray: [
{ "id": 0, "name": "Not Available" },
{ "id": 1, "name": "Not Ready" },
{ "id": 2, "name": "Not Started" }
]
};
console.log(merge(user));
Sure :)
let arrayOfObjects = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
const newValues = ['Not Available', 'Not Ready', 'Not Started'];
newValues.forEach((value, i) => {
arrayOfObjects.find(o => o.id === i).name = value;
});
console.log(arrayOfObjects);
I wouldn't recommend this though: functional programming is awesome.
let arrayOfObjects = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
let names = ['Not Available', 'Not Ready', 'Not Started']
let result = arrayOfObjects.map((user, index) => ({ ...user, name: names[index] }))
console.log(result)

Convert one Multidimensional JSON array to another

I have the following input object
{
"id": 1,
"isLeaf": false,
"name": "New rule",
"pid": 0,
"dragDisabled": true,
"children": [
{
"id": "new1",
"value": "data1",
"then": false,
"type": "set",
"forEach": false,
"pid": 1
},
{
"id": "new2",
"value": "data2",
"then": true,
"type": "if",
"forEach": false,
"pid": 1,
"children": [
{
"id": "new3",
"type": "Then",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new5",
"value": "data3",
"then": false,
"type": "fuzzy_search",
"forEach": false,
"pid": "new3"
}
]
},
{
"id": "new4",
"type": "Else",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new6",
"value": "data4",
"then": false,
"type": "return",
"forEach": false,
"pid": "new4"
}
]
}
]
}
]
}
I need to convert it into the following json
[
{
"id": "new1",
"condition": "data1"
},
{
"id": "new2",
"condition": "data2",
"then": [{
"id": "new5",
"condition": "data3"
}],
"else": [{
"id": "new6",
"condition": "data4"
}]
}
]
I have to recursively iterate through all existing inner child array of the input json array to formulate the output.
Following is the partially implemented code for the functionality.
ruleJSONFormatter = (request, parentItem, innerJSON) => {
try {
var outerObject = request;
if (outerObject.children && outerObject.children.length) {
var innerArray = outerObject.children;
// second iteration with inner children
innerArray.forEach((innerItem, index) => {
let parentObj = {};
let recursiveObj = {}; let thenArray = [];
recursiveObj['condition'] = innerItem.value && innerItem.value != undefined ? innerItem.value.formatedData : {};
recursiveObj['type'] = innerItem.type;
recursiveObj['id'] = innerItem.id;
recursiveObj['pid'] = innerItem.pid;
if (innerItem.children && innerItem.children != undefined && innerItem.children.length) {
switch (innerItem.type) {
case 'if':
recursiveObj['then'] = [];
recursiveObj['else'] = [];
}
if (Object.keys(parentObj).length == 0) {
parentObj = recursiveObj;
} else {
}
ruleJSONFormatter(innerItem, parentItem, parentObj)
} else {
if (Object.keys(parentObj).length == 0)
responseArray.push(innerJSON);
}
});
}
else {
console.log("No Values Inside the Formated Data ")
}
console.log("output-----------");
console.log(JSON.stringify(responseArray));
return responseArray
} catch (error) {
console.log('((((((((((((((((((((((((((', error)
}
}
final output array has a condition key which binds the value key from the input json and 'then' key which contains the multiple successive inner children array which is the success condition for type 'if' object. similar is the case for 'else' key in output
I find it hard to recursively call the same function to generate the desired output. the problem arises when there are deep nesting in the children array.Any help is appreciated.Thanks.

javascript extract objects from nested arrays using a list of ids

I have a list of ids as reference, and I have an object which contains multiple objects that have array of objects.
I want to make an array of objects with corresponding ids in the list, the FASTEST way.
const data = {
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
};
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val) {
const match = Object.keys(data.items).map(item => {
return data.items[item].find(obj => obj.id === val)
});
results.push(match)
})
console.log('final: ', results)
the current is not returning what i want.
the expected result will be:
[
{
"id": "id2",
"info": "info22"
},
{
"id": "id4",
"info": "info6"
}
]
update:
How about in the case if the data is itself an array of objects, and we want to do the same for each one?
const data = [{
"otherStuff": "otherB",
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
}, {
"otherStuff": "otherA",
"items": {
"item1": [{
"id": "id1",
"info": "info10000"
},
{
"id": "id2",
"info": "info220000"
}
],
"item20": [{
"id": "id3",
"info": "info5000"
}],
"item5": [{
"id": "id4",
"info": "info60000"
},
{
"id": "id5",
"info": "info7000"
}
]
}
}];
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val) {
data.forEach(function(entry){
Object.keys(entry.items).forEach(item => {
var match = entry.items[item].find(obj => obj.id === val);
if (match) {
results.push(match)
}
});
});
})
console.log(results)
and the output should be:
[
{
"otherStuff": "otherB",
"items": [
{
"id": "id2",
"info": "info22"
},
{
"id": "id4",
"info": "info6"
}
]
},
{
"otherStuff": "otherA",
"items": [
{
"id": "id2",
"info": "info220000"
},
{
"id": "id4",
"info": "info60000"
}
]
}
]
the result is not the same though.
If you use a Set for the kept ids, you save one O(n) traversal:
const keep = new Set(['id4', 'id2']);
const result = [];
for(const items of Object.values(data.items))
for(const item of items)
if(keep.has(item.id))
result.push(item);
You do not need to use map(). Simply use forEach() loop on the object keys which you want to keep and find the matching object so that it can be pushed into the result array.
const data = {
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
};
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val) {
Object.keys(data.items).forEach(item => {
var match = data.items[item].find(obj => obj.id === val);
if (match) {
results.push(match)
}
});
})
console.log('final: ', results)
items is an object & item1,item20 are are keys.So you can do Object.values and apply reduce function on it to get a single array which is consist of all the objects. No iterate the keep array and filter out the required element from the single array.
const data = {
"items": {
"item1": [{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [{
"id": "id3",
"info": "info5"
}],
"item5": [{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
};
const keep = ['id4', 'id2'];
let getAllObjectValues = Object.values(data.items).reduce(function(acc, curr) {
curr.forEach((elem) => {
acc.push(elem)
})
return acc;
}, []);
let k = keep.map(function(item) {
return getAllObjectValues.filter(function(val) {
return item === val.id
})[0]
})
console.log(k)
You've used an assignment operator rather than an equivalence operator in your map function, change to:
const keep = ['id4', 'id2'];
const results = [];
keep.forEach(function(val){
const match = Object.keys(data.items).map(item => {
return data.items[item].find(obj => obj.id === val)
});
results.push(match)
})
console.log('final: ', results)
Using a combination of reduce and filter you can iterate each sub-array checking whether the value should be kept.
const data = {
"items": {
"item1": [
{
"id": "id1",
"info": "info1"
},
{
"id": "id2",
"info": "info22"
}
],
"item20": [
{
"id": "id3",
"info": "info5"
}
],
"item5": [
{
"id": "id4",
"info": "info6"
},
{
"id": "id5",
"info": "info7"
}
]
}
};
const keep = ['id4', 'id2'];
const filter = el => {
return keep.indexOf(el.id) >= 0;
};
const reducer = (accumulator, currentValue) => {
return accumulator = accumulator.concat(data.items[currentValue].filter(filter));
};
let results = Object.keys(data.items).reduce(reducer, []);
console.log('final: ', results);

transform property using map failed got unexpected token error

I have nested array of object structure look like this
const resp = [
[
{
id: 1
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
]
I use ES6 to truncate the name property, base on 'en':
resp = resp.map(o => ({
...o,
o.map(o2 => ({ //unexpected token
...o2,
name: o2.name.en.value
})
)
})
)
But I got the unexpected token error?
I want to produce this result
//expected output
const resp = [
[
{
id: 1
name: "something"
}
]
]
const resp = [
[{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}]
];
const result = resp.map(o => {
return o.map(o2 => {
return {
id: o2.id,
name: o2.name.en.value
}
})
});
console.log(result);
This can also be achieved using Array.reduce() function, other than using Array.map() as #AushGupta has answer. The detailed description and answers are at MDN.
const resp = [
[
{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
},
{
id: 3,
"name": {
"en": {
"language": "en",
"value": "newthing"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
],
[
{
id: 2,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
];
var result = resp.reduce((results, current) => {
var items = current.reduce((items, item) => {
items.push({
id: item.id,
name: item.name.en.value
});
return items;
}, []);
results.push(items);
return results;
}, []);
console.log(result);
<html>
<body>
</body>
</html>
Use .map on the array and you just need to return an object with id and name.
const resp = [
[
{
id: 1,
"name": {
"en": {
"language": "en",
"value": "something"
},
"id": {
"language": "th",
"value": "something else"
}
}
}
]
];
let result = resp[0].map(
el => {return {"id": el.id, "name": el.name.en.value}}
);
console.log(result);
You might need to wrap result in another array.

Categories

Resources