Creating a nested Json from an array - javascript

I have this Js array:
const a = [
[
"Paris",
"75000"
],
[
"Toulouse",
"31000"
],
[
"Marseille",
"13000"
]
];
How to convert restructure this array to JSON?
[{
"city": "Paris",
"zip": "75000"
},
{
"city": "Toulouse",
"zip": "31000"
},
{
"city": "Marseille",
"zip": "13000"
}]
I tried with the JSON.stringify() function but I don't get the expected result.
Thanks

Youre array declaration isn't correct. This is the correct syntax for declaring an array in JS and using JSON.stringify on it:
tab = [
{city: 'Paris', zip: '75000'},
{city: 'Toulouse', zip: '31000'},
{city: 'Marseille', zip: '13000'}
];
JSON.stringify(tab, null, 2)

You could use Array.prototype.map to convert sub-array entries of the original array into objects with suitably named properties, and call JSON.stringify on the result.
const tabs = [
[
"Paris",
"75000"
],
[
"Toulouse",
"31000"
],
[
"Marseille",
"13000"
]
];
// restructure sub-arrays into objects:
let objectArray = tabs.map(entry=> {
const [city, zip] = entry;
return {city, zip};
})
// Stringify object array
let jsonText = JSON.stringify( objectArray, null, 2)
console.log(jsonText);
The map function is using Destructuring assignment to extract city and zip values from each sub-array.
A null second and numeric third parameter supplied to JSON.stringify improve human readability of the output but are generally omitted in production environments to reduce the length of network messages.

Related

How to remove duplicates form object of arrays [duplicate]

This question already has answers here:
map function for objects (instead of arrays)
(39 answers)
Closed 3 months ago.
I am trying to remove duplicate form list of arrays that are present in an object and object looks like bellow , for example i am only using two array but there are many in actual array that i am looking at
{
"NAME":[
"LORD",
"OF",
"RINGS",
"LORD"
],
"ADRESS":[
"INDIA",
"INDIA",
"TEXAS",
"SRILANKA"
]
}
Expected output :
{
"NAME":[
"LORD",
"OF",
"RINGS"
],
"ADRESS":[
"INDIA",
"TEXAS",
"SRILANKA"
]
}
Currently I am able to pull out a single array from object and am able to remove duplicates using "SET" bellow is my code
console.log("without duplicates", [... new Set(r.NAME)]);
Since it is an object i am sure i cant loop on this. How can i achieve the expected output , Thanks
You can iterate over the object keys and then use Set to remove duplicates like so:
function removeDuplicates(obj): any {
for (const key of Object.keys(obj)) {
obj[key] = [...new Set(obj[key])];
}
return obj;
}
const obj = {
NAME: ["LORD", "OF", "RINGS", "LORD"],
ADDRESS: ["INDIA", "INDIA", "TEXAS", "SRILANKA"]
};
//get array of keys
const keys = Object.keys(obj);
//then map to transform the object array
const sets = keys.map(key => new Set(obj[key]));
//set back to array
keys.forEach((key, i) => {
obj[key] = [...sets[i]];
});
console.log(obj);
We can use Set to remove the duplicate
let data = {
"NAME":[
"LORD",
"OF",
"RINGS",
"LORD"
],
"ADRESS":[
"INDIA",
"INDIA",
"TEXAS",
"SRILANKA"
]
}
Object.keys(data).forEach(k => {
data[k] = [...new Set(data[k])]
})
console.log(data)
How about this way?
const originDatas = {
"NAME":[
"LORD",
"OF",
"RINGS",
"LORD",
],
"ADRESS":[
"INDIA",
"INIDA",
"TEXAS",
"SRILANKA",
],
};
const setDatas = {};
Object.keys(originDatas).map((key) => {
setDatas[key] = [...new Set(originDatas[key])];
});
console.log(setDatas);

Adding a Object Array in a Array into a JSON

I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});

javascript - accessing specific data in an array of objects

How do I pick the first value of rowVal of the first object (I want to print 42.00).
dataTest.rows = [{
"rowHeader": "",
"rowDesc": ["Gene Name"],
"rowVal": [
["42.00", "57.00", "45.00", "48.00", "52.00", "47.00", "39.00", "38.00", "35.00"]
]
}, {
"rowHeader": "",
"rowDesc": ["Gene Source"],
"rowVal": [
["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
]
}];
I tried:
console.log(dataTest.rows[0].rowVal[0]);
but it returns all the numbers in the array of rowVal of the first object?
rowVal is an Array of Arrays. That's why you get that result.
"rowVal": [
["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
]
See, when you say rowVal[0], it refers to an array. So, ideally, it should be something like
"rowVal": ["38.00", "50.00", "39.00", "41.00", "45.00", "40.00", "34.00", "33.00", "29.00"]
if you want to access the elements as rowVal[0]. Or else, you have to change your reference to rowVal[0][0].

Testing for an object key in an array of objects using mocha and chai

If I have an object that is an array of objects
{ "places": [ {city: "Pittsburgh", state: "PA"} ] }
how do I test to see if the array at index 0 (places[0]) has an object with a key "city"? I tried this but it didn't work
expect( {"places": [ {"city": "Pittsburgh", "state": "PA"} ] } ).to.nested.include({"places[0]" : "city"});
You should use to.have.nested.property instead of to.nested.include:
var obj = {"places": [ {"city": "Pittsburgh", "state": "PA"} ] };
expect(obj).to.have.nested.property("places[0].city");

Reduce javascript object

I have this javascript object :
{
{
long_name: "10",
types: [
0: "street_number"
],
},
{
long_name: "street",
types: [
0: "route"
],
},
{
long_name: "Paris",
types: [
0: "locality"
],
},
...
}
And I want to flatten it and have something like :
{
street_number: "10",
route: "street",
locality: "Paris",
...
}
I am using ES6, but can't manage to flatten it this much,
All I've succeeded to do is having :
{
{street_number: "10"},
{route: "street"},
{locality: "Paris"},
...
}
Here is what I Tried :
const flattenedObject = originalObject.map(flatten);
...
function flatten(element) {
let obj = {};
obj[element.types[0]] = element.long_name;
return obj;
}
Thanks for any help.
You could use Array#reduce with a computed property and the first element only from the array.
The key feature is Object.assign for adding properties to the result object.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var data = [{ long_name: "10", types: ["street_number"], }, { long_name: "street", types: ["route"], }, { long_name: "Paris", types: ["locality"], }],
object = data.reduce((r, a) => Object.assign(r, { [a.types[0]]: a.long_name }), {});
console.log(object);
All I've succeeded to do is having:
{
{street_number: "10"},
{route: "street"},
{locality: "Paris"},
...
}
I don't how you "succeeded" in getting that, since no such kind of object exists in JS (nor does your original object). Did you mean to put [] around it instead of {} (in other words, is it an array of little objects)? If so, then combine with
Object.assign({}, ...littleObjects)
By the way, you can call this "flattening" if you want, but it will be confusing, since it's quite different from what people usually refer to as "flattening" (meaning to collapse nested arrays).

Categories