I have two dimensional JSON array. I can take data from first dimension like data["dimension-1"] however i cannot take data from second dimension like: data["dimension-1"]["dimension-2"]. What is the proper way to take single row from second dimension of my array?
data["dimension-1"]["dimension-2"] - seems to be rather an object - hence it should look like :
var data = {
"dimension-1" : {
"dimension-2" : 'value'
}
}
data["dimension-1"]["dimension-2"] // will display 'value'
and then your way it ok.
but if it's an array
var data =[[1,2], [3,4]]
then one should access it like (the indexes are NUMERIC - not strings or any other):
data[0][1] // will display 2
You have an object with properties that are also a mixture of arrays or objects. If you are trying to extract the ID of the data property, which is an array, then you will need to select the property, enter the array (first item is 0), which returns another object. Then just select the property.
You'll need something like the following in your use case: -
objectName.data[0].id
or
objectName["data"][0]["id"];
This is for extracting the ID from within the data attribute in data like this (that you provided): -
var objectName = {
"total_pages": 1424,
"total_rows": 1424,
"data": [
{
"id": 1525,
"television_id": 1,
// other stuff
"categories": [
{
"id": 170,
"title": "title"
},
{
"id": 4,
"title": "message"
}
]
}
]
}
A 2 dimensional JSON array looks like this:
[
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]
]
Say you want to access the last column in the second column. i.e. "f", then you need to access it by number not name. i.e.:
data[1][2]
EDIT:
Stictly speaking, my original answer is correct. Your 2 dimensional array may be accessed by indices.
However, knowing the format of your data now, I would recommend either:
Use a library (e.g. lodash) to give you simple and expressive ways to query your data
or create your own function. e.g.:
var category = getCategory(x.data, 1525, 170);
function getCategory(data, id, catId) {
return data
.filter(d => d.id === id)
.map(d => d.categories
.filter(c => c.id === catId)
.map(c => c.title)
.shift()
)
.shift()
}
Good luck!
Related
NOTE: I know what I'm attempting to do logically doesn't make sense in terms of why I want to achieve this, however I just want to know if it's possible and if so what I might be writing wrong?
I'm working with an array of objects like so:
this.animalsAndFruits = [
{
"category": "Apple",
"num1": 1287,
"num2": 12956
},
{
"category": "Panda",
"num1": 2574,
"num2": 25826
},
....
]
This may seem tedious and rather ridiculous however using the array I want to return the word 'category', not the value just the key 'category'.
I've tried
this.objectFromArray[0].category
However it only returns the value of the 0th indexed item (even though the 0th indexed item key will always have key 'category')
Is there another way I can accomplish this?
P.S. The reason why I want to get 'category' is because I need to set a variable = 'category', however I don't want to hardcode it directly like this
var someVar = 'category'
If it helps, the value in the key:value pair where the key = category is always a string (whereas all of the other values under different keys are numbers.
Maybe logic like so might work =>
if(value = string) then return key ?
Since the non-category properties have a consistent format (num#, right? at least going by the prior question), if you want to find the key which does not start with num, you can use Object.keys to get an array of keys, then .find the key matching the condition:
const animalsAndFruits = [
{
"category": "Apple",
"num1": 1287,
"num2": 12956
},
{
"category": "Panda",
"num1": 2574,
"num2": 25826
},
];
const propertyName = Object.keys(animalsAndFruits[0]).find(
key => !key.startsWith('num')
);
console.log(propertyName);
If you happen to be able to depend on the non-num key always being the first one defined in the objects, you could also use Object.keys(animalsAndFruits[0])[0].
SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)
Hi I have following objects in an array and they appear like this:
[{col1:abc}
{col2:def}
{col1:ghi}]
What I want to do is if the same key is coming again I should overwrite it so it becomes
[{col1:ghi}
{col2:def}]
instead of appending another key value pair.
I am thinking of something like to overwrite
[col1:{col1:ghi}
col2:{col2:def}]
so that i can easily iterate over them in future.
Is there any way to put my keys in this way by using map or something similar?
Thank you
I'm going to assume all your objects look like the ones you provided in your question, i.e. they each are a single key-value pair (like {col1: "abc"})
We first need to loop over all the objects in your array, combining them into one large object. Since an object cannot have two identical keys, this has the effect of overwriting values associated with a key that occur earlier in the array with ones that associate with the same key, but occur later. This can be achieved with:
const unifiedObj = arr.reduce((acc, obj) => Object.assign(acc, obj), {})
reduce is a way of "looping" over the items in an array (well, not exactly, but you can think of it this way for now). Object.assign is a way to merge two objects. You should look these up in the MDN docs.
So now, if your original array looked like this:
[
{col1:"abc"}
{col2:"def"}
{col1:"ghi"}
]
The "unified" object will look like this:
{
col1: "ghi",
col2: "def"
}
Next, since you want an array of 'single key-value pair objects' as your final result, instead of this unified object, we're going to have to extract each key-value pair in the unified object into a new object, and collect all those new objects into an array. That's what this statement does.
const result = Object.keys(unifiedObj).map(k => ({k: unifiedObj[k]}))
Object.keys gives you all the keys of an object as an array. map transforms an array into another array, using the function supplied as its argument. Look these up too.
At the end, result will be an array that looks like this:
[
{ col1: "ghi" },
{ col2: "def" }
]
which seems to be what you wanted. Do note that the objects in the array might be in a different order from what you expect, i.e. the final array may also look like this:
[
{ col2: "def" },
{ col1: "ghi" }
]
This is quite an easy task! The explanation is in the code comments.
const arr = [{col1:'abc'},
{col2:'def'},
{col1:'ghi'}]
arr.forEach((item, index) => {
// get the key `col1`, `col2` etc. (only works if there is one key in the object!)
const key = Object.keys(item)[0]
// now check if the key was previously encountered
for (i = 0; i < index; i++) {
if (arr[i][key] !== undefined) {
// the same key was found in the already processed chunk of the array! Rewrite it with the latter value!
arr[i][key] = item
}
}
})
console.log(arr)
I think you probably want to produce a single object from your array of objects and retain all values for the same key, so that
[
{col1: 'abc'},
{col2: 'def'},
{col1: 'ghi'}
]
becomes
{
col1: ['abc', 'ghi'],
col2: ['def']
}
if that sounds right, then here's how to do it:
const arr = [
{col1: 'abc'},
{col2: 'def'},
{col1: 'ghi'}
];
const result = arr.reduce((memo, o) => {
Object.entries(o).forEach(([key, val]) => {
memo[key] = memo[key] || [];
memo[key].push(val);
});
return memo;
}, {});
console.log(result)
I have an object that I need to transform into an array. Here is the code I have already:
for (var key in categoryData[p]) { // categorydata is an object, the "p" is because this is taking place in a loop (array of objects)
if (categoryData[p].hasOwnProperty(key)) {
var objToArray = $.map(categoryData[p], function(value, key) {
return [value];
});
}
}
Right now, this is returning:
0 : value
1 : value
2 : value
I want it to return:
Key : Value
Key : Value
Key : Value
But I haven't found a way to do this with my data. Any direction would be greatly appreciated!
Edit: Adding more information:
I want to sort from the highest to lowest value. For clarification, I want the data to look like this:
(key) (object)
"ABC" : 8
"DEF" : 7
"GHI" : 5
I am putting it into an array to begin with because I can't sort the values when they're in an object (as far as I know).
My data is fairly complex, in a CSV file, but the idea of it is:
ABC, DEF, GHI
8 , 7 , 5
Associative arrays aren't a thing in javascript. You can either have arrays denoted by [] with 0 based numeric indices, or objects denoted by {} that can store key-value pairs. The latter construct can be used as replacement to associative arrays (ie add arbitrary keys and values to it), but they cannot be treated like arrays.
What you want in this case is what you already have - a key/value store, except it's called an object.
edit
If you just want to sort the data regardless of datatypes
You can split your object into multiple objects with a single key-value pair, then create an array from these objects and sort them any way you like using Array.sort(). Here's a quick example of splitting your provided data into objects:
var originalData = {
"ABC" : 8,
"DEF" : 7,
"GHI" : 5,
},
sortableArray = [];
for (key in originalData) {
sortableArray.push({
"key" : key,
"value" : originalData[key]
});
}
This creates a new object and appends it to our sortable [] array. To sort it according to its original value, you need to supply a comparator function that accesses the value property of the objects.
sortableArray.sort(function(a,b) {
return a.value - b.value;
});
This should return an array of objects ordered by the value property of each object in ascending order. Simply switch a and b around to get a descending order sort.
Hope this helps!
The best approach to sort your data is to map your object into an array to look like this:
[
{
"key": someKey
"value": someValue
},
{
"key": someOtherKey
"value": someOtherValue
},
//...
]
using this code:
var objToArray = $.map(categoryData[p], function(value, key) {
return {"key": key, "value": value};
});
And then sort it using this code:
objToArray.sort(function(a, b) {
// if the values are numbers (otherwise you have to change this to addapt to your dataType)
return b.value - a.value; // to sort from highest to lowest or a.value - b.value to sort from lowest to highest
});
And then you can use it like:
objToArray[0].key; // to get the key of the first item
objToArray[3].value; // to get the value of the 4-th item
// ...
You can loop through them as well (for(var i = 0; i < objToArray.length; i++)...).
In ES6, Object.entries(a).sort((a, b) => a[1] < b[1] )
This will give you something like this
[
["ABC", 8]
["DEF", 7]
["GHI", 5]
]
the .entries step gives you the list of pairs and the .sort step sorts them by their second value
I'm trying to filter some JSON data to search for job roles that starts with a certain string.
The JSON looks like :
"periods": [
{
"periodName": "Week1",
"teamName": "Tango",
"roleName": "SoftwareEngineerII",
"roleExperience": "2",
"id": "cc1f6e14-40f6-4a79-8c66-5f3e773e0929"
},
...
]
I want to filter for roleName that starts with "Software" so that I can see a list of all Software Engineer levels, and it filters out other roles.
I'm not sure how to do a "starts with" or "contains" here.
You are trying to filter the array where one of the string properties contains a value... How else would you check if a string contains another string?
You could use a regex:
var str = 'SoftwareEngineerII';
if (str.match(/^software/i)) {
// it starts with 'software'
}
So you need to convert this to a predicate that could be used in your filter.
var query = Enumerable.From(data.periods)
.Where("!!$.roleName.match(/^software/i)")
.ToArray();