I have a JSON array whose general structure is like this:
var json = [
{ key: 'firstName', value: 'Bill' },
{ key: 'lastName', value: 'Mans' },
{ key: 'phone', value: '123.456.7890' }
];
In reality, there will be a lot more key/value pairs. Either way, I'm trying to sort this array by the key value using Lodash. Currently, I'm trying the following:
_.map(_.sortBy(json, key), _.values);
However, that causes an error that says:
[ReferenceError: key is not defined]
I suspect its because key is not wrapped in quotes as shown in the docs. Unfortunately, I do not actually have control over the format of the json. In reality its being used by other developers and I'm the last to use it. Is there a way for me to sort the json array, by key names, using lodash? If so, how?
thank you
You need to put the key in quotes only when calling sortBy. It doesn't have to be in quotes in the data itself.
_.sortBy(json, "key")
Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.
_.pluck( _.sortBy(json, "key") , "value");
_.map(_.sortBy(json, 'key'), 'value');
NOTE: In the latest version of lodash, _.pluck no longer exists. Use _.map instead as a drop-in replacement
Related
I have an object of objects and I'd like to use a v-for loop to llop through all the objects except the first two ones, sadly I can't use slice sice it's only for arrays, is it possible to remove the first wo elements of an object using javascript without creating a new object
My object is something like:
{
First: { },
Second: { },
Third: { }
}
I am not that pro in js but first check this url
How to loop through a plain JavaScript object with the objects as members?
this just to get maybe an idea
How can I slice an object in Javascript?
so I will give you a logic where you may get a solution
if you won't get answer from above
when finished from url and get clear understand
create a function where it iterate over objects
from what I suggest
then create a variable =1
if var_inc==1 or var-==2
continue
else
do whatever
then do a for loop to loop over over objects
then do that function
just get the logic maybe you get it..
❤🌷😅
JS objects don't store the order of elements like arrays. In the general case, there is no such thing as order of specific key-value pairs. However, you can iterate through object values using some utility libraries (like underscore https://underscorejs.org/#pairs), or you could just use raw js to do something this:
// this will convert your object to an array of values with arbitrary order
Object.keys(obj).map(key => obj[key])
// this will sort keys alphabetically
Object.keys(obj).sort().map(key => obj[key])
Note that some browsers can retain order of keys when calling Object.keys() but you should not rely on it, because it isn't guaranteed.
I would suggest to just use array of objects to be sure of order like this:
[{ key: "First", value: 1 }, { key: "Second", value: 2}]
If you just want to delete the properties of the objects then you can use delete keyword.
delete Obj['First']
delete Obj['Second']`
This would delete both the keys and object would have only 'Third' key
Looking for clean way to convert a javascript object containing arrays as values to a search param compatible query string. Serializing an element from each array before moving to the next index.
Using libraries such as querystring or qs, converts the object just fine, but handles each array independently. Passing the resulting string to the server (which I cannot change) causes an error in handling of the items as each previous value is overwritten by the next. Using any kind of array notation in the query string is not supported. The only option I have not tried is a custom sort function, but seems like it would be worse than writing a custom function to parse the object. Any revision to the object that would generate the expected result is welcome as well.
var qs = require("qs")
var jsobj = {
origString:['abc','123'],
newString:['abcd','1234'],
action:'compare'
}
qs.stringify(jsobj,{encode:false})
qs.stringify(jsobj,{encode:false,indices:false})
qs.stringify(jsobj,{encode:false,indices:false,arrayFormat:'repeat'})
Result returned is
"origString=abc&origString=123&newString=abcd&newString=1234&action=compare"
Result desired would be
"origString=abc&newString=abcd&origString=123&newString=1234&action=compare"
I tried reorder your json:
> var jsobj = [{origString: 'abc', newString: 'abcd' }, {origString: '123',
newString: '1234' }, {action:'compare'}]
> qs.stringify(jsobj,{encode:false})
'0[origString]=abc&0[newString]=abcd&1[origString]=123&1[newString]=1234&2[action]=compare'
But I don't know if this is a good alternative for your problem.
Chalk this up to misunderstanding of the application. After spending some more time with the API I realized my mistake, and as posted above by others, order does no matter. Not sure why my first several attempts failed but the question is 'answered'
I have a map which i am populating from a json file, similar to the below
key: ConfigItem
value: Var1,Var2,Var3
key: ConfigItem2
value: Var1,Var2,Var3,var4
key: ConfigItem3
value: true
i want to be able to run an if statement to check if a value is contained within the "ConfigItem" key, and if so, do something.
I looked at map.get and map.has but i can't seem to be able to figure out how to search a specific key and return if it contains a specific value.
You seem to be looking for
const map = new Map([
["ConfigItem", ["Var1","Var2","Var3"]],
["ConfigItem2", ["Var1","Var2","Var3","var4"]],
["ConfigItem3", true],
]);
if (map.get("ConfigItem").includes("Var2")) {
…
}
Notice this just uses Map get to access the array value for the ConfigItem key, but then uses the normal Array includes method to check if the specific string is contained in it.
I'm writing a unit test in Jest.
In the unit under test I am importing
import queryString from 'query-string'
and it is executing the code:
queryString.stringify(ids)
where ids is an array in the following format:
[{ id: '123' },{ id: '321' }]
This code works perfectly when running in my deployed webpage, but in a JEST test it gives the following output:
id=%5Bobject%20Object%5D&id=%5Bobject%20Object%5D
whereas the same code in a browser gives:
id=123&id=321
As per the requisites of the query-string module, I am using a verison of node > 6.
I have also added:
/* jest commonjs */
to the top of my test file as query-string targets node.
Additionally I have tried setting various options in stringify but to no avail.
Can anyone tell me why I'm getting different results in these different environments and how I can get my test to work? i.e. not render the string as "%5Bobject%20".
Sure, I could implement my own stringify method, but this library is built to do this!
Can you please define what the expected behavior would be?
According to the documentation, stringify() converts an object into a query. Since you are passing ids, an array of elements, there are different possible behaviors you may get.
Please note that, in javascript, an array is an object with numbers as keys, so [ { id: '123' }, { id: '456' } ] actually looks like { '0': { 'id': '123' }, '1': { 'id': '456' } } (take a look at Object.keys of the array, you'll see it's ['0','1']).
So, that being said, what queryString is doing is converting each pair key-value into key=value, where both key and values have been "stringified" (I'm assuming through the String constructor). Since the value is an object, it returns that things you're seeing (indeed, String({}) is [object Object]. What I would expect (and I'm indeed getting) from the stringification of an array of objects is therefore something like 0=[object Object]&1=[object Object] (with the square brackets converted to %5B and %5D and spaces to %20).
I don't really know where that questionId is coming from, so a little more context should be provided (e.g. showing the actual object being stringified could be useful) but, to get to the point, in order to avoid having your object be converted to [object Object] you should use a key extractor, that returns the value you actually want to be shown as value.
So, for example, if your array is as described above and the result you'd like to get is 0=123&1=456, you would do something like:
const ids = [ {id: '123'}, {id: '456'} ];
queryString.stringify(ids.map(v => v.id))
Instead, if the expected behavior is id=123&id=456, you need to convert the array to the object { id: ['123','456'] }. You can do that with the following
const ids = [ {id: '123'}, {id: '456'} ];
queryString.stringify({ id: ids.reduce( (c,v) => c.concat(v.id), []) })
So, you need to transform your original ids array into an object that is suitable for stringify.
You can use this npm package https://www.npmjs.com/package/qs
It has a working qs.stringify
This is my JSON object:
{ text: 'stuff',
user: 'user1
}
when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.
So how can I properly access everything in JavaScript?
I don't want to use jQuery as this is all node.js programming so it's serverside.
UPDATED - full JSON
{ text: '#junk_666 おかえりか',
user:
{ display_name: 'mono',
screen_name: 'monochrm',
klout_score: null,
location_str: '画面の前',
utc_offset: '32400' },
venue_id: 1304409836517,
match_type: 'twitter',
tweet_id: '116494264137023489',
created_at_unix: 1316609371,
meta:
{ matchedPhrase: 'junk',
venueName: 'deletemepls really long name' },
tags: [ '' ],
indexed_at_unix: 1316609416 }
The json seems to be invalid
{
"text": "stuff",
"user": "user1"
}
I copied and pasted your object into a FireBug console and it recognized it.
If you need to count the number of key/value pairs, you can use a function such as this one to do it:
function numMembers(o) {
var i=0;
for (a in o) {
i++;
}
return i;
}
You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.
First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.
Secondly, JavaScript objects in general do not have a length property. Arrays do.
There's no problem with your object literal so there must be some other problem elsewhere in your code.
Try this:
{ text: 'stuff',
user: 'user1'
}
You left off an apostrophe.
Now that you've posted your full JS code (that's not JSON, as #josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.