My data is currently stored in this format, stored in a JSON file:
{
"name": {
"0": ______,
"1": ______,
"2": ______
},
"xcoord": {
"0": ______,
"1": ______,
"2": ______
},
"ycoord": {
"0": ______,
"1": ______,
"2": ______
}
}
And I need to convert it into this format, as an array of objects:
[
{
"id": 0,
"name": _____,
"xcoord": _____,
"ycoord": _____
},
{
"id": 1,
"name": _____,
"xcoord": _____,
"ycoord": _____
},
{
"id": 2,
"name": _____,
"xcoord": _____,
"ycoord": _____
}
]
As you can see, I also need to take the number keys in my first data format and make them the "id" values in my second data format. (Since the position of the object in the array and the id number match up, maybe that would be another way to create the "id" key?) I would then store my second data format into a local variable to use in my JS code.
Any ideas on how I can do this? I'm not very good with restructuring this kind of data.
This can be done for instance with two imbricated .forEach():
var obj = {
"name": {
0: 'name0',
1: 'name1',
2: 'name2'
},
"xcoord": {
0: 'xcoord0',
1: 'xcoord1',
2: 'xcoord2'
},
"ycoord": {
0: 'ycoord0',
1: 'ycoord1',
2: 'ycoord2'
}
};
var res = [];
Object.keys(obj).forEach(k => {
Object.keys(obj[k]).forEach(v => {
(res[v] = (res[v] || { id: v }))[k] = obj[k][v];
});
});
console.log(res);
Note:
This line ...
(res[v] = (res[v] || { id: v }))[k] = obj[k][v]
... is a short way to do:
if(!res[v]) {
// if this record doesn't exist yet,
// create it with its implied 'id' property
res[v] = { id: v };
}
// add property 'k' to this record
res[v][k] = obj[k][v];
Related
I want to compare 2 json and return error message for which object or value is not match
For example:
json1 = {
"id": 1,
"product": {
"productId": "456",
"product_detail": [
{
"name": {
"value": 1
}
},
{
"name": {
"value": 2
}
}
]
}
}
json2 = {
"id": 1,
"product": {
"productId": "123",
"product_info": [
{
"name": [{
"value": 3,
}
},
{
"name": {
"value": 4
}
}
]
}
}
I was using try / catch on each object and value, however, it is complicated process to const each propriety. Therefore, i am looking for another way to do the checking
My expected error message result should return all object / value is not matching in test result:
Failed - json2 > product_info propriety not matching with json
Failed - json2 > product.product_detail.name[0].value : 3 not equal with json1 > product.product_detail.name[0].value :1
Failed - json2 > product.product_detail.name[1].value : 4 not equal with json1 > product.product_detail.name[1].value :2
If there are no error found > return message pass
are you sure you need recursion for that?
Checkout lodash isEqual function: https://lodash.com/docs/#isEqual
Here's the data.
[{
"id": 1,
"type": "tv",
"name": "name1"
},
{
"id": 2,
"type": "movie",
"name": "name2"
},
{
"id": 3,
"type": "person",
"name": "name3"
},
{
"id": 4,
"type": "tv",
"name": "name4"
}]
The method I used is below:
Currently my code doesn't create types dynamically. Declare an array and push it.
I want to make the type dynamic, but I don't know how.
Is there a better way?
const movieList = [], tvList = [], personList = [];
arr.forEach(e=>{
switch (e.type) {
case 'movie':
movieList.push(e);
break;
case 'tv':
tvList.push(e);
break;
case 'person':
personList.push(e)
default:
break;
}
});
Thanks for your help
There is Array.prototype.group but it's still experimental and not supported in all environments. So in the meantime, you could use a function similar to it. This one returns an object with the keys given. You can destructure the returned object and rename the keys to get a specific group as well:
const data = [{"id":1,"type":"tv","name":"name1"},{"id":2,"type":"movie","name":"name2"},{"id":3,"type":"person","name":"name3"},{"id":4,"type":"tv","name":"name4"}];
function group(array, getKey) {
const out = {};
array.forEach((item) => {
const key = getKey(item);
if (!(key in out)) out[key] = [];
out[key].push(item);
});
return out;
}
const {
movie: movieList,
tv: tvList,
person: personList,
} = group(data, (item) => item.type);
console.log(movieList);
console.log(tvList);
console.log(personList);
I have a javascript variable, call it temp, that is holding value input by a user. For example,
const temp=10
I want to update an object property to this variable value.
For example, I want to change
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": "null",
"entry": 1
}
]
to
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": value of the javascript variable 'temp',
"entry": 1
}
]
I've tried just including the variable like this:
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": "temp",
"entry": 1
}
]
and this
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": temp,
"entry": 1
}
]
and neither worked. Is there an easy way to do this?
var data = [{"1":"1.5","2":"2","subject_input":"null","entry":1}]
const temp = "temp data";
data = data.map(o => ({...o, subject_input: temp}));
console.log(data);
//or directly assigning temp to subject_input
var data2 = [
{
"1":"1.5",
"2":"2",
"subject_input":temp,
"entry":1
}
];
console.log(data2);
I have an array of values as follows
[
{
"factor": {
"data": "f1",
"val": [
"val1"
]
}
},
{
"factor": {
"data": "f2",
"val": [
"val2"
]
}
}
]
Is there a way to convert it to below format
{
"keyvalue": {
"factor": {
"data": "f1",
"val": ["val1"]
},
"factor": {
"data": "f2",
"val": ["val2"]
}
}
}
Standard array parsing to object doesn't work in this case given keys has to be unique
It's impossible. Every key in the object has to be unique. To understand this, imagine you have an object with two identical keys:
const obj = {
"key": 1,
"key": 2
}
But what you should receive when you use an expression like obj.key? 1 or 2? It's nonsense.
You should rethink your object structure, maybe you need an array of objects?
{
"keyvalue": {
"factor": [
{
"data": "f1",
"val": ["val1"]
},
{
"data": "f2",
"val": ["val2"]
}
]
}
}
What you can do is use the data field as a key given it's always unique.
Something like this :
{
"factor": {
"f1": ["val1"],
"f2": ["val2"]
}
}
Here's how you would proceed to transform the array to the key/value object :
let keyValue = {"factor": {}};
theArray.forEach((item) => {
const key = item.factor.data;
const value = item.factor.val;
keyValue.factor[key] = value;
});
now the keyValue object is as described.
I have this nested object (json):
const json = {
"application": {
"App1": {
"cats": [
1
]
},
"App2": {
"cats": [
3
]
},
"App3": {
"cats": [
1,
2
]
}
},
"categories": {
"1": {
"name": "FirstCategory"
},
"2": {
"name": "SecondCategory"
},
"3": {
"name": "ThirdCategory"
}
}
};
This object has two main properties: application and categories.
I want to map over application's cats array and get name property of each element of cats array.
So the final result should look like:
{
"App1": "FirstCategory",
"App2": "ThirdCategory",
"App3": "FirstCategory, ThirdCategory"
}
I have tried to use map function, but the main difficulty is that inside applicaiton property cats is array (can have multiple values). So the code below didn't work:
Object.values(json.application).map(val => {
Object.keys(json.categories).map(key => {
//print something
});
});
You can use Array.reduce for an elegant solution.
const json = {
"application": {
"App1": {
"cats": [
1
]
},
"App2": {
"cats": [
3
]
},
"App3": {
"cats": [
1,
2
]
}
},
"categories": {
"1": {
"name": "FirstCategory"
},
"2": {
"name": "SecondCategory"
},
"3": {
"name": "ThirdCategory"
}
}
};
//Getting Application object
const application = json.application
//Getting Categories object
const categories = json.categories
//initializing reduce with a blank object and pushing all the keys of the application object
//Looping over keys of application object
const requiredOutput = Object.keys(application).reduce((out, appKey) => {
//Setting value based on categories name
out[appKey] = application[appKey].cats.map(id => categories[id].name)
return out
}, {})
console.log(requiredOutput)
PS: You can refer this gist for safe reading from a nested object.
Try it with this.
for(let val in json.application){
json.application[val] = json.application[val].cats.map(cat => json.categories[cat].name).join(",")
}
const result = Object.keys(json.application).reduce((a,key) => {
a[key] = json.application[key].cats
.map(cat => json.categories[cat].name)
.join(", ")
return a;
}, {})
loop over keys of application
for each key loop over car, and for each cat return string value from category
join list of cat strings