How can I set a jsonarray inside the jsonobject?
I want to be able to push the values but I do not know exactly what to do
sample :
{
"ContactsDetails": [
{
"Prefix": "string",
"FirstName": "string",
"LastName": "string",
"Mobile": "string",
"EmojiId": "byte"
}
],
"GroupId": integer
}
Here is the sample code what you're looking for.
let empty = {}; // init a empty object.
empty["ContactsDetails"] = []; // array creation
empty["GroupId"] = 45; // number adding
// creating a new object
let c_details = {
"Prefix": "string",
"FirstName": "string",
"LastName": "string",
"Mobile": "string",
"EmojiId": "byte"
};
// adding an existing obj to array, push operation
empty["ContactsDetails"].push(c_details);
// print object
console.log(empty);
// this will convert the object to JSON.
console.log(JSON.stringify(empty))
What you call a JSONArray is simply a Javascript array like []. You can set it like any property of an Object (JSON).
In Javascript, an Object (symbolized as {}) will be represented as a JSON Object and a Array (symbolized by []) will be represented as a JSON Array.
So you can just do something like this :
var object = {};
object.foo = [];
object.foo.push("newvalue");
object.foo.push("bar");
console.log(object);
And of course, you can push an Object in your array like this :
var array = [];
array.push({ foo: "bar" });
console.log(array);
Arrays and objects are structures that can recursively contain themselves, or each other. JSON is just a format that represents these recursive data structures.
Luckily, you can define all of these in JavaScript using plain literals:
An array literal is wrapped within brackets []
An object literal is wrapped within curly brackets {}
Hence, you can build an array of objects:
[
{name: 'x', data: 0},
{name: 'y', data: 1}
]
Or an object that its parameters are arrays:
{
array0: [0, 1],
array1: [2, 3]
}
And, as I mentioned above, you can also use these structures recursively. For example:
[
{id: 0, array: [0, 1]},
{id: 1, array: [2, 3]}
]
Related
Given an array of dictionaries in javascript, I want to merge them so that they don't contain any duplicates. For example given
jsons1 = [{"a": "xyz"}, {"a": 12}]
jsons2 = [{"a": "xyz"}, {"a", 13}]
I want to return a new array that removes the duplicates while merging
jsons3 = [{"a": "xyz"}, {"a": 12}, {"a": 13}]
order isnt important
This is what I did:
let jsons1 = [
{
"a": "xyz"
},
{
"a": 4
},
{
"a": 1
},
]
let jsons2 = [
{
"a": "xyz"
},
{
"a": 4
},
{
"a": 6
},
]
const val = [jsons1, jsons2]
let filtered = []
for(json of val) {
for(obj of json) {
let match = false;
for(dict of filtered) {
if(JSON.stringify(dict) === JSON.stringify(obj)) {
match = true;
break
}
}
if(match == true) {
continue
}
filtered.push(obj)
}
}
console.log(filtered)
https://jsfiddle.net/awb6qnzo/6/
Basically I create a new array called filtered and I then iterate through each jsons array. I then iterate through filtered to check if that obj is already in it.
although it works, its extremely inefficient. Is there a simpler way?
Edit: Changing question to specific values since the former is apparently not possible
Given an array of dictionaries in javascript, I want to merge them so that they don't contain any duplicates (on the key "id"). E.g.
jsons1 = [{"id": 1}, {"id": 12}]
jsons2 = [{"id": 1}, {"id": 3}]
I want to return a new array that removes the duplicates while merging
jsons3 = [{"id": 1}, {"id": 3}, {"id": 12}]
Let's reword the problem and pretend we have a function equals that checks if two objects are the same, first.
We want to concatenate all the values in jsons2 that satisfy some condition.
To do that, we need to filter out objects that don't satisfy the condition.
This condition is that every object in jsons1 does not equal the object in jsons2.
Another way to put this is the negation of some object in jsons1 is equal to the object in jsons2.
jsons1.concat(
jsons2.filter(
(a) => !jsons1.some((b) => equals(a, b))
)
);
You can write equals anyway you want, as long as it functions correctly.
This question already has answers here:
Converting an Array to an Object
(3 answers)
Closed 2 years ago.
I am having troubles converting an array into an object of keys and values.
Currently, I have the following nested array:
var array = [[id1, parent1, "name1", "desc1"], [id2, parent1, "name2", "desc2"], [id3, parent1, "name3", "desc3"]];
Where the length of the array is dynamic.
For my code, I require the array to be converted such that it is an object of keys and values (consisting of the first (id) and third (name) value of each nested array).
For example, the object for the above array would be as follows:
var obj = {id1: name1, id2: name2, id3: name3};
Where the id values (id1, id2, id3) would be the corresponding integer values.
I apologise if a similar question has been asked before, but I couldn't seem to find a similar question which had a solution that worked for me.
Any help or advice would be greatly appreciated!
You can use a simple for loop to do it
var array = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent1", "name2", "desc2"],
["id3", "parent1", "name3", "desc3"]
];
const obj = {}
for (const item of array) {
obj[item[0]] = item[2];
}
console.log(obj);
After using Array.map to extract the first and third entries from each element in the array, you can then use Object.fromEntries to convert the extracted array of key/value pairs into an object:
const [id1, id2, id3, parent1] = [1, 2, 3, 4];
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
const obj = Object.fromEntries(array.map(a => [a[0], a[2]]));
console.log(obj);
You basically want to convert your original array into an array of [key, value] pairs. You can then use the Object.fromEntries function to convert those key/values into an object. So, something like this:
const arr = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent2", "name2", "desc2"],
["id3", "parent3", "name3", "desc3"],
];
const results = Object.fromEntries(arr.map(x => ([x[0], x[2]])))
console.log(results)
As a good practice, it is recommended to use let or const instead of var because var "pollute" the global namespace, so that's what my example will use.
However, if you need to use var, you can replace const with var inside my example and it will still be okay.
Given the following source array:
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
The following block of code create an object named obj using the 1st element of the sub-array as a key, and the 3rd element as the value:
// Create an empty object
const obj = {};
// Iterate through the source array
array.forEach((element) => {
// Assign the 1st element of the sub-array as the property key
// and the 3rd element as the property value
obj[element[0]] = element[2];
});
console.log(obj);
And this has the same effect, but simpler and with a smaller footprint:
const obj = Object.fromEntries(array.map(([key, _, value]) => [key, value]));
console.log(obj);
I have the following json example:
{
"MyTest:": [{
"main": {
"name": "Hello"
},
"test2": {
"test3": {
"test4": "World"
},
"test5": 5
}
},
{
"main": {
"name": "Hola"
},
"test6": [{
"name": "one"
},
{
"name": "two"
}
]
}
]
}
I'm trying to convert it to an array of arrays with key-values
[[main.name: "Hello",test2.test3.test4: "World", test2.test5: 5] ,
[main.name = "Hola", test6.name: "one", test6.name: "two"] ];
Looking for some function like "is leaf" - so I will know that is the value.
Any advise for deep iteration will be very appriciated.
The flattenObject() function returns an object of one level, with the keys built from all sub keys. The recursive function checks if the current value is an object. If it is, it iterates the object with _.flatMap() and calls itself on each property with the keys collected so far. If the value is not an object, it returns an object with a single property (the joined keys), and the value.
It then merges the array of { key: value } objects to a single object.
const flattenObject = val => {
const inner = (val, keys = []) =>
_.isObject(val) ? // if it's an object or array
_.flatMap(val, (v, k) => inner(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
{ [keys.join('.')]: val } // return the joined keys with the value
return _.merge({}, ...inner(val))
}
const obj = {"MyTest":[{"main":{"name":"Hello"},"test2":{"test3":{"test4":"World"},"test5":5}},{"main":{"name":"Hola"},"test6":[{"name":"one"},{"name":"two"}]}]}
const result = obj.MyTest.map(flattenObject)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
I have a JSON array of objects in JS that look something like this:
"data": [
{"name": "abc", "location": "NY", "value": 1234, "potato": "tomato", "someOtherProp": "prop1"},
{"name": "def", "location": "CA", ... etc}
{etc ...},
]
I'm creating a UI for filtering down some of these fields and want to create an array for each attribute with all the given values in the data.
I know this is possible using something like this:
let result = objArray.map(a => a.name);
But using this strategy, I have to run map once for every property. Is there any way to only go through the array once but create a separate array for each? (Or is there a better way in general for creating filter options for a UI?)
To clarify, for the array above, I'd want an array for "names" (containing "abc" and "def"), an array for "locations" (containing NY, CA, etc.) an array for "potato"s and "someOtherProp".
I appreciate any help!
Thanks
Loop through the array with .reduce(). In each iteration, loop through the keys of the object using Object.keys(), adding any unique values to an array of the same name.
This solution eliminates duplicate entries and works with any amount of properties.
const data = [{name: "abc", location: "NY"},{name: "def", location: "CA"},{name: "xyz", location: "TX"},{name: "zyx", location: "TX"}];
const getFiltersFromData = (data) => {
return data.reduce((out,obj) => {
Object.keys(obj).forEach(k => {
if (out[k] === undefined) out[k] = [obj[k]]; //Array doesn't exist yet - instantiate it
else if (!out[k].includes(obj[k])) out[k].push(obj[k]); //Array exists and this value isn't in it - add the value to it
});
return out;
}, {});
};
const filters = getFiltersFromData(data);
console.log(filters.name);
console.log(filters.location);
.as-console-wrapper, .as-console { height: 100% !important; max-height: 100% !important; top: 0; }
You could create the separate arrays from names, locations and values and then use map on the data array to push each attribute value to the arrays. You can do that vs. running map multiple times for each property:
var names = [];
var locations = [];
var values = [];
data.map((elt) => {
names.push(elt.name);
locations.push(elt.location);
values.push(elt.value);
});
Try with Object.entries
You can get something like this:
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
I have a array of object like this
AnArray: [
{ name: 'name1',
id: 123456,
arrayOfSomething: [[1], [2], [3]]
},
{ name: 'name2',
id: 123456,
arrayOfSomething: [[0], [2], [1]]
}
I need to push just the arrayOfSomething array in the result array, so I do:
SaveMyResult(){
this.result.push({
something:this.AnArray})
}
but it pushing me all the object data, How can I do ?
If you push AnArray, then yes, the result will be that AnArray is added to the end of your results array. If you don't want that, and you only want one property from each object, use the map method and concatenate the final array it creates:
this.result = this.result.concat(this.AnArray.map(({arrayOfSomething}) => ({arrayOfSomething})));
Here I've used a bit of destructuring to shorten the code, but it's basically going through every element of the array, pulling out its arrayOfSomething property, and replacing the element with a new object that contains only that property.