I got a very common question but with a twist which is the reason for this post:
I want to create a key,value object from a string.
my string looks like this:
01§§foo§§bar§§someLink
(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)
now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.
i want to generate something like this:
var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];
the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.
Thank you in advance
You could use Array#split for the string and an array for the keys.
var string = '01§§foo§§bar§§someLink',
moduleKeys = ["ID", "title", "description", "link"],
object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
console.log(object);
A methode for multiple strings.
function getData(array) {
var moduleKeys = ["ID", "title", "description", "link"];
return array.map(function (string) {
var object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
return object;
});
}
var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));
Related
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I have such a object and array which I received response from my server. I need to convert that to second format at below in order to print the value in the website. Is this something need to do object mapping? or parse JSON or please kindly help.
{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]},
Convert from Above to below
'{"SEOUL" : "38", "BUSAN" : "CAPITAL", "NAMPODONG" : "M31"}'
var finalObj = {};
response.header.forEach(function(item, index) {
finalObj[item] = response.data[0][index];
});
Above code is working fine as it create variable and loop for header and get its value and printed in html. the header and data are from the server so when I enter something let say "A" then it will look for SEOUL header then print 38 in html as tables are looks below.
key value : A
header : SEOUL BUSAN NAMPODONG
data : 38 CAPITAL M31
I do have a lot of data in the database, above is just an example. So let say I enter B then the B is not in database so I want to see the value "No found" in html but this code printing nothing so not sure whether it was proceed or not.
Create a variable & loop over the object.header to get each key and object.data[0] to get its value
var myObj = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
}
var tempObj = {};
myObj.header.forEach(function(item, index) {
tempObj[item] = myObj.data[0][index]
})
console.log(tempObj)
As you received it from server – I assume that it is JSON string.
Basically you have two arrays here that you want to reduce to an object.
So I would do it like this:
const object = JSON.parse('{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}');
const result = object.header.reduce(function(accumulator, element, i){
accumulator[element] = object.data[0][i] // You had nested array here so I have to get first element.
return accumulator;
}, {});
console.log(result);
I assumed that nested array for data attribute is some kind of formatting mistake. If it's not – you have to map though it's elements first and only then reduce.
You can use zipObj from Ramda library.
The code would look like this:
const res = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}
const obj = R.zipObj(res.header, res.data[0])
console.log(obj)
<script src="//cdn.jsdelivr.net/npm/ramda#latest/dist/ramda.min.js"></script>
You could map the new objects with the wanted keys.
The result is an array with objects, because your data is a nested array with actually only one array. But it looks like taht data could contain more than one row.
var data = { header: ["SEOUL", "BUSAN", "NAMPODONG"], data: [[38, "CAPITAL", "M31"]] },
result = data.data.map(a => Object.assign(...data.header.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map the data array of arrays into another array of object using as keys the strings in header array:
function transform(obj) {
return obj.data.map(function(subArray) { // for each subArray in the data array
return subArray.reduce(function(o, val, i) { // create a new object o which...
o[ obj.header[i] ] = val; // has key-value pairs where value is the current element of subArray and key is its equivalent (item at the same index) from header array
return o;
}, {});
});
}
var obj = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"], [10,"OTHER","M01"]]};
var result = transform(obj);
console.log(result);
I think the responses above are good as they are, but here is an alternative using reduce in case you didn't know about it
var response = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
};
var result = response.header.reduce(function(accum, v, i) {
accum[v] = response.data[0][i];
return accum;
}, {})
console.log(result)
I have this function which takes a json parameter which contains an array of search objects.
function receiveSearch(search, json) {
return {
type: RECEIVE_SCHOOL_SEARCH,
items: json.packages,
receivedAt: Date.now(),
search: Object.assign({}, search, { next: json.next, start: search.next }),
};
}
My json
property looks like:
>0:Object
>1:Object
>2:Object
>3:Object
...{ more }
I would like to return to the search object two properties from json i.e name and suburb. How do I do this? I would prefer to use something neat like lodash/ramda/underscore but plain js is fine.
And each object contains the following properties:
id:"10360"
centreId:776
name:"ABBOTSFORD"
suburb:"TARNEIT"
The easiest solution to you problem using JavaScript could be make a new object which contains only required property and return that.
Just assume your json looks like this:
var x = {search:{id:"10360",centreId:776,name:"ABBOTSFORD",suburb:"TARNEIT"},otherProp:val}
To get required properties, you can make another function and return the object with required fields:
function ReturnRequiredPropertyObject(anyObj)
{
var newObj = {};
newObj.search = {};
newObj.search.name = anyObj.search.name;
newObj.search.suburb = anyObj.search.suburb;
return newObj;
}
You can put the above code in loop if you are getting an array of search object.
To make the above code generic, we can do the following:
function ReturnRequiredPropertyObject(anyObj,requiredPropertyArray)
{
var newObj = {};
for(var counter = 0;counter<requiredPropertyArray.length;counter++)
{
newObj[requiredPropertyArray[counter]] = anyObj[requiredPropertyArray[counter]];
}
return newObj;
}
Hope this will help.
Ok resolved.
Answer is
_.map(json,_.partialRight(_.pick,['name','suburb']));
I'm trying to restructure an object for convience.
This is the general structure:
var dictionary = { "word": {"content": "wordy"}, "palabra": {"content":"palabrota" }};
I want it to look like this:
[{"wordy":"word"},{"palabrota":"palabra"}]
And I'm trying this code out:
_.map(dictionary, function(v,k){ var new_key = v.content;return { new_key: k };} );
But instead of what I am expecting, this is the result:
[ { new_key: 'word' }, { new_key: 'palabra' } ]
How to get a key to be used as a variable in this function?
You can use the _.invertBy method (as of LoDash v4.1.0), which will give you the key and an array of the values, thus ensuring the values aren't overwritten.
var dictionary = {
"word": {"content": "wordy"},
"anotherWord": {"content": "wordy"},
"palabra": {"content":"palabrota" }
};
var result = _.invertBy(dictionary, function(item) {
return item.content;
});
// "{"wordy":["word","anotherWord"],"palabrota":["palabra"]}"
EDIT: earlier response below. This works, however the limitation is duplicate content values would overwrite the keys. The docs for _.transform below shows how to generate an array to handle duplicates, and a similar setup can be used for the regular JS approach.
You can use the _.transform method:
var transformedResult = _.transform(dictionary, function(result, value, key) {
return result[value.content] = key;
});
Or without LoDash at all, you can construct the object as intended.
var result = {};
Object.keys(dictionary).forEach(function(key) {
var value = dictionary[key].content;
result[value] = key;
});
I might recommend _.mapValues(dictionary, "content") for simplicity.
However, instead of [{"wordy":"word"},{"palabrota":"palabra"}], instead you'll get {"wordy": "word", "palabrota": "palabra"} as the result from _.mapValues. But given that you're using lodash, and lodash treats arrays and objects pretty much interchangeably, I think the non-array version would be more convenient.
I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]