How to handle a nested json array to show in a table? - javascript

I have this JSON array. I am displaying data in a table. So, How should I put 'transactionData' inside the main object? i.e. I want the object as
{
completeTime: "value",
createTime: "value2",
assigneeName:"value3",
assigneeMap:"value4"
}
Since this is a JSON Array, so I need a way to iterate the array and make each of the objects as required.
I can't use the original JSON array since the object transactionData is not fixed and its keys might change. So, I don't want to hardcode any value like assigneeMap or assigneeName as it might change.
Hence, I want whatever the values in transactionData object are there, I want to insert it into my main object.

use the array.map(), something like this
results.map(x=>{
{
completeTime: x.completeTime,
createTime: x.createTime,
assigneeName: x.assigneeName || x.assigneename,
assigneeMap:x.assigneeMap || x.assigneeMap || x.yourChangedKey,
}
})

Use Array.prototype.map()
const result = arr.map(item => {
const { completeTime, createTime, data: { transactionData } } = item;
const { assigneeName, assigneeMap } = transactionData;
return {
completeTime,
createTime,
assigneeName,
assigneeMap
}
});

Related

Converting arrays nested in array into object using forEch (does not work somehow?)

I am having trouble with something i thought it will be simple.
I have an array of nested arrays with strings.
const cities = [['Vienna'],['Berlin'],['London'],['Oslo'],['New York']]
I must convert these nested arrays into objects. I think forEach method should suit perfectly along with Object.assign.
I written something like these:
function convert(element) {
Object.assign({}, element)
}
const Test = cities.forEach(convert)
But then i am getting from console.log(Test) undefinded. Why so ? I am iterating through the whole array and each of her arrays should be assign as object. Whats missing ?
Object should contain key: value pair
If you want to convert each string element into an object element. Then you can do something like this :
const cities = [['Vienna'],['Berlin'],['London'],['Oslo'],['New York']]
const res = cities.map((item) => {
return {
city: item[0]
}
});
console.log(res);

What's an elegant way to filter an object with an array list for empty elements and sort it in preferred order? (Javascript, Node.js)

I have a Dialogflow cloud function that gets a parameters object from an user input.
When I type in Dialogflow: "I am working in the garden" it basically creates this parameters object:
var parametersObject = {
nouns: ["garden"],
pronounsDefinite: ["I"],
verbsHelpPresent: ["am"],
articles: ["the"],
verbsGerund: ["working"],
prepositions: ["in"],
verbsInfinitiv: [],
adverbsTime: [],
};
Now my plan is to write all the necessary data to Firebase in some kind of order.
I would like to filter all parameters with this array list here, which also gives my preferred order:
var listOfParameters = [
"pronounsDefinite",
"verbsInfinitiv",
"verbsGerund",
"articles",
"nouns",
];
and then create a new list of non empty objects with the order from my listOfParameters:
var listOfNonEmptyObjects = [];
This listOfNonEmptyObjects is then written to Firebase.
Right now I add all the objects to listOfNonEmptyObjects like this:
try {
const pronounsDefinite = agent.parameters.pronounsDefinite[0];
listOfNonEmptyObjects.push({ "pronounsDefinite": pronounsDefinite });
} catch (error) { }
try {
const pronounsDefinite1 = agent.parameters.pronounsDefinite[1];
listOfNonEmptyObjects.push({"pronounsDefinite1":pronounsDefinite1});
} catch (error) {}
try {
const verbsInfinitiv = agent.parameters.verbsInfinitiv[0];
listOfNonEmptyObjects.push({ "verbsInfinitiv": verbsInfinitiv });
} catch (error) { }
try {
const verbsGerund = agent.parameters.verbsGerund[0];
listOfNonEmptyObjects.push({ "verbsGerund": verbsGerund });
} catch (error) { }
try {
const articles = agent.parameters.articles[0];
listOfNonEmptyObjects.push({ "articles": articles });
} catch (error) { }
try {
const nouns = agent.parameters.nouns[0];
listOfNonEmptyObjects.push({ "nouns": nouns });
} catch (error) { }
So I get this:
listOfNonEmptyObjects = [
{ pronounsDefinite: "I" },
{ verbsGerund: "working" },
{ articles: "the" },
{ nouns: "garden" },
];
I also set "ignoreUndefinedProperties: true" which leaves out empty elements (In this case verbsInfinitiv which has no value).
Is there a more elegant way, maybe with a forEach function that looks up every entry in listOfParameters, then checks if parametersObject has a non empty element and after that adds it to the listOfNonEmptyObjects?
Edit: I added an example what happens if for example the pronounsDefinite parameter contains more than one element (e.g. pronounsDefinite: ["I", "You", "He", "She"],), so if the user puts in several words that match the pronounsDefinite entity. Then I would get this parameter as pronounsDefinite1 in my try catch block.
You need to loop over the listofParameters first. Then for each parameter, you need to check if the parameter exists in parametersObj. You can do this using the in operator. In that same if condition, you can also check if the value of parametersObj is empty or not. If both conditions are met, you can then push the value into your listOfNonEmptyObjects
var listOfNonEmptyObjects = []
listOfParameters.forEach(parameter => {
if (parameter in parametersObject && parametersObject[parameter].length > 0) {
listOfNonEmptyObjects.push({[parameter]: parametersObject[parameter]})
}
})
Completely Unrelated
You can use Filter and Map. Object.entries converts the object into a tuple of key and value. Then you can filter the empty value (ie, second element of tuple). Finally you can map over and construct your desired array
Object.entries(parametersObject) // Split the parameters object into an array of key-value pairs.
.filter(([k, v]) => v.length) // Accept only non-empty parameters by checking the parameter array length.
.map(([k, v]) => ({[k]: v[0]})) // Convert each key-value pair in the array into an object.
My take with after learning from boxdox's solutions:
var parametersObject = { nouns: ['garden','a random addition for testing'], pronounsDefinite: ['I'], verbsHelpPresent: ['am'], articles: ['the'], verbsGerund: ['working'], prepositions: ['in'], verbsInfinitiv: [], adverbsTime: []}
var listOfParameters = ["pronounsDefinite", "verbsInfinitiv", "verbsGerund", "articles", "nouns"];
var listOfNonEmptyObjects = [];
// Let's go through each of the listed parameters
listOfParameters.forEach( parameter =>
// If such a parameter exists in parametersObject, handle each one of its values.
(parametersObject[parameter]||[]).forEach((item, index) =>
// Push each value as an object into the list of non empty objects
listOfNonEmptyObjects.push({[parameter+(index?index:'')]: item})
)
);
console.log(listOfNonEmptyObjects);

Filter JSON data with jquery

Hi I have a JSON format of the following -
{
"0":{
"name":"example",
"age":"21"
},
"1":{
"name":"example2",
"age":"22"
}
}
I want to convert it to the following format with jQuery -
{
"name":"example",
"age":"21"
},
{
"name":"example2",
"age":"22"
}
removing numbering from keys. Please suggest.
You really do not need JQuery for this. You can use Object.values() function to get an array of values for each property in the object:
const input = {
"0":{
"name":"example",
"age":"21"
},
"1":{
"name":"example2",
"age":"22"
}
}
const result = Object.values(input)
console.log(result)
I assume your desired result is an array.
var json = JSON.parse("your json");
var keys = Object.getOwnPropertyNames(b);
for(var i=o;i<keys.length;i++){
console.log(b[keys[i]]);
}
Here you go "numbering" removed is over btn Storing parsed objects should be stored in collections, and keys are required to exist in objects. please refer to

Fetch values of key-value in array of objects

I'm trying to display the values of all key-value pairs in an array of objects. I've tried several methods, for example http://jsfiddle.net/4Mrkp/, but I can't seem to get it to work on my data.
The data, I want to display the car makes only:
{
"response":{
"status":"200",
"messages":{},
"milliseconds":"2"
},
"input":{
"provinceid":{},
"supplierid":"12345678",
"statusid":{ }
},
"output":{
"count":"7",
"list":{
"make":[
{"name":"Alfa Romeo"},
{"name":"Audi"},
{"name":"BMW"},
{"name":"Chevrolet"},
{"name":"Chrysler"},
{"name":"Citroen"},
{"name":"Dacia"}
]
}}
}
My code so far, this displays the word make:
function display_makes(obj)
{
document.getElementById("temp-id").innerHTML =
Object.keys(obj.output.list.make).forEach(function(key){
document.write(key);});
}
So next step is to fetch the values of each element of make, but how? Any thoughts?
Don't use Object.keys on obj.output.list.make because it's an array, use:
obj.output.list.make.forEach(function(obj) {
console.log(obj.name);
});
You may use underscoreJS for manipulating the JSON.
var make = _.map(json_object.output.list.make,function(make) {
document.write(make.name);
return make;
})
This make variable will contain values in key-value pair.
It is easier than you think. Just iterate over the array and forget about the rest:
object.output.list.make.forEach(function(item){
document.write(item);
});
You are working with the array therefore you do not need at all the Object.keys()

Trouble Sorting JSON

I have a JSON object like the following:
{"Data": {
"290": {
...
}
"300": {
...
}
"281": {
...
}
}
}
How would I sort this JSON based on the top container keys (i.e. "290", "300", "281")?
Edit: So I used
$.getJSON('current/csf.txt', function(data) { arr = data["Data"]; }
And it sorted them based on the key. Why did this happen?
You've tagged this "JavaScript" so I assume you mean "A JavaScript object generated from this JSON".
In which case:
Loop over the property names (with a for in loop).
Use them to populate an array.
Sort the array.
Use the array as a map.
(You can't store ordered data in an object).
If you want to store the results in JSON, then you will need to change your data structure (and use an array (of objects)). Objects are explicitly unordered.
Your structure is wrong, it should be something like:
{
"Data": [
{
"id": "290"
},
{
"id": "300"
},
{
"id": "282"
}
]
}
Objects are for unordered data. Use arrays for ordered data. And the array is really easy to sort here:
obj.Data.sort(function(a,b){
return a.id - b.id;
});
You can convert to this structure like so:
function copyProps(dest, src) {
for (var key in src) {
dest[key] = src[key];
}
return dest;
}
var newData = [];
for (var key in obj.Data) {
newData.push(copyProps({
id: key
}, obj.Data[key]));
}
I agree with Amberlamps comment, you shouldn't be trying to sort the keys of an object, but if you wanted to for some reason you might take a look at underscore.js's sortBy method
Even if you COULD sort object attributes, there's no guarantee that you could read them back in sorted order. In Javascript, object attributes are not stored in a specific order; an object simply has attributes.
You cannot use array index notation to access object attributes, so the notion of sorting object attributes by key is moot.

Categories

Resources