Easy way to extract json object properties into an array? - javascript

Given the following JSON object, is there an easy way to extract just the values of the results object properties?
var j={"success":true,
"msg":["Clutch successfully updated."],
"results":{"count_id":2,
"count_type":"Clutch",
"count_date":"2000-01-01",
"fish_count":250,
"count_notes":"test"}
};
var arr= doSomething(j.results);
//arr=[2, "Clutch","2000-01-01",250,"test"]

Your function would be something like
var doSomething = function (obj) {
var arr = [];
for (var x in obj) if (obj.hasOwnProperty(x)) {
arr.push(obj[x]);
}
return arr;
}

function resultstoArray (resultsData) {
var myArray = new Array();
for (var key in resultsData) {
myArray.push(resultsData[key]);
}
return myArray;
}
var arr = resultsToArray(j.results);

Related

Mapping string with key-value pair to object

Given the following string with key-value pairs, how would you write a generic function to map it to an object?
At the moment, I am just splitting by : and ; to get the relevant data, but it doesn't seem like a clean approach.
This my code at the moment:
var pd = `id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74`;
var tempPd = pd.split(';');
for (i = 1; i < tempPd.length; i++) {
var b = tempPd[i].split(':');
console.log(b[1]);
}
What about using reduce:
function objectify(str) {
return str.split(";").reduce(function (obj, item) {
var a = item.split(":");
obj[a[0]] = a[1];
return obj;
}, {});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));
or:
function objectify(str){
return str.split(";").reduce((obj,item)=>{
var a = item.split(":");
obj[a[0]]=a[1];
return obj;
},{});
}
var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74";
console.log(objectify(strObj));

parse json object in javascript to get key and values

I have a object, need to parse the below data
var data= [{"obj1":"2122"},{"obj2":"123"}]
to get both the keys and values in javascript. I yried to use:
var obj = JSON.parse(data);
for(var prop in data) {
if(data.hasOwnProperty(prop))
console.log(prop);
}
The values that are obtained in console are
Object {obj1: "2122"}
Object {obj2: "123"}
But I need to access the values seperately and not as object. How to retrieve it from that object?
JSON.parse is use to parse JSONString to Javascript Object.
You can not use it directly on a JavaScript Object ...
Anyway, your object is an array so you may do :
var arr = JSON.parse(data);
arr.forEach(function(elementObject){
var keys = Object.keys(elementObject);
keys.forEach(function(key){
console.log(key + ":"+elementObject[key]);
})
});
Cheers
Here you will get the values in array "values".
var data= [{"obj1":"2122"},{"obj2":"123"}]
data = JSON.stringify(data);
var values = [];
JSON.parse(data, function (key, value) {
if (typeof(value) != "object") {
values.push({[key]:value});
// values.push(value); //if you need a value array
}
});
Use Array#map and extract keys of the object in the callback. Iterate them to gain the value of each key using Array#forEach
var data = [{
"obj1": "2122"
}, {
"obj2": "123"
}];
var op = data.map(function(item) {
var keys = Object.keys(item);
var arr = [];
keys.forEach(function(key) {
arr.push(item[key]);
});
return arr;
});
console.log(op);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Try this code use $.each function to parse object..
var data= [{"obj1":"2122"},{"obj2":"123"}]
$.each(data, function(key, val) {
$.each(val, function(k, v) {
console.log('key ='+k);
console.log('value ='+v);
alert('key = '+k+', value = '+v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this one..
var obj = JSON.parse('[{"obj1":2122},{"obj2":123}]');
obj.forEach(function(ElementObject){
var keys=Object.keys(ElementObject);
console.log(keys[0],ElementObject[Object.keys(ElementObject)]);
}
);
JsFiddle
First:
var data = [{"obj1":"2122"},{"obj2":"123"}]
This line will create an Array. No need for:
var obj = JSON.parse(data);
If you want to access via key/value you need to restructure your data.
var data = [{key:"obj1",value:"2122"},{key:"obj2", value:"123"}];
for( var index in data)
{
var item = data[index];
console.log(item.key);
console.log(item.value);
}
Alternately you can map:
var keys = [{
"obj1": "2122"
}, {
"obj2": "123"
}];
var op = data.map(function(item) {
var keys = Object.keys(item);
var arr = [];
keys.forEach(function(key) {
console.log(key);
arr.push(key);
});
return arr;
});
var i=0;
for(var i=0;i<op.length;i++)
{
console.log(i);
var pair=data[i];
console.log(pair);
var key=op[i][0];
console.log(key);
var value=pair[key];
console.log(value);
}

how to get preferred array pushed in javascript

I am receiving data in object form. that object contains properties in which three keys are holding array values. I want to push concat those three array into one master Array. But should be in preferred sequence. Like
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
oneArray(obj,'make','type','power')
The master Array should have first 'make', 'type' and then 'power' keys Array from object. Right now it is coming in order which is given in obj
Fidde
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function (obj,first,second,third){
var newObj = obj;
var list = [];
for(var key in newObj){
if (newObj[key] instanceof Array) {
if (!list) {
list = newObj[key];
}
else {
list = list.concat(newObj[key]);
}
}
}
newObj['all'] = list;
return newObj
}
console.log(oneArray(obj,'make','type','power'))
I'm not sure I have understood your question, but try this...
This onArray() function takes parameters that indicating priorities in orderly manner but first parameter.
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function(obj) {
var newObj = obj;
var list = [];
var priorityList = arguments;
for( var i = 1 ; i < priorityList.length ; i++ ) {
if( newObj[ priorityList[i] ] instanceof Array ) {
for( var key in newObj[ priorityList[i] ] ) {
list.push( newObj[ priorityList[i] ][ key ] );
}
}
}
newObj['all'] = list;
return newObj;
}
console.log(oneArray(obj,'make','type','power'));

How to recursively merge 2 javascript objects?

I have 2 objects that I need to merge and keep all properties in tact, tried with jQuery $.extend but I cant get it to work . I tried all posts with how to merge javascript objects but simply cant get this to work.
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"]};
var fa_icon_source = {"Spinners":["faspinner1","faspinner2"],"Awesome":["faawesome1","faawesome2"]};
var new_source ={};
$.extend(new_source,fa_icon_source,thz_icon_source);
console.log(thz_icon_source);
console.log(fa_icon_source);
console.log(new_source);
desired output should be like
{
"Spinners":["faspinner1","faspinner2","spinnericon1","spinnericon2"],
"Awesome":["faawesome1","faawesome2","awesomeicon1","awesomeicon2"]
}
This post Merge two json/javascript arrays in to one array has a simple object mine is not same as that one.
Demo
function mergeJSON(json1,json2)
{
var result = json1 ;
for (var prop in json2)
{
if (json2.hasOwnProperty(prop))
{
result[prop] = result[prop].concat(json2[prop]);
}
}
return result;
}
$.extend merges in missing properties, it doesn't combine the properties that are in common. You need to write a loop.
var thz_icon_source = {
"Spinners": ["spinnericon1", "spinnericon2"],
"Awesome": ["awesomeicon1", "awesomeicon2"]
};
var fa_icon_source = {
"Spinners": ["faspinner1", "faspinner2"],
"Awesome": ["faawesome1", "faawesome2"]
};
var new_source = {};
// First add in the new elements from thz_icon_source
$.extend(new_source, fa_icon_source, thz_icon_source);
// Now merge the common elements
$.each(fa_icon_source, function(k, e) {
if (thz_icon_source.hasOwnProperty(k)) {
new_source[k] = e.concat(thz_icon_source[k]);
}
});
console.log(thz_icon_source);
console.log(fa_icon_source);
console.log(new_source);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use this prototype to merge 2 or more objects the way you want it:
Object.prototype.assignDeep = function() {
var self = this;
Object.keys(arguments).forEach(obj => {
Object.keys(self).forEach(val => {
if (arguments[obj].hasOwnProperty(val)) {
var tmp = arguments[obj][val] instanceof Array ? arguments[obj][val] : [arguments[obj][val]];
self[val] = self[val].concat(tmp);
}
});
});
return self;
}
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"]};
var fa_icon_source = {"Spinners":["faspinner1","faspinner2"],"Awesome":["faawesome1","faawesome2"]};
var b = thz_icon_source.assignDeep(fa_icon_source);
console.log(b);
You should use a loops with .concat():
function objectConcatArrays(){
var a = arguments, o = {};
for(var i=0,l=a.length; i<l; i++){
for(var p in a[i]){
if(p in o){
o[p] = o[p].concat(a[i][p]);
}
else{
o[p] = a[i][p];
}
}
}
return o;
}
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"]};
var fa_icon_source = {"Spinners":["faspinner1","faspinner2"],"Awesome":["faawesome1","faawesome2"]};
var res = objectConcatArrays(thz_icon_source, fa_icon_source);
console.log(res);
Each argument represents an Object of Arrays. Add more if you want.

Converting js array into dictionary map

I have this array:
["userconfig", "general", "name"]
and I would like it to look like this
data_structure["userconfig"]["general"]["name"]
I have tried this function:
inputID = "userconfig-general-name"
function GetDataByID(inputID){
var position = '';
for (var i = 0; i < inputID.length; i++) {
var hirarchy = inputID[i].split('-');
for (var index = 0; index < hirarchy.length; index++) {
position += '["'+ hirarchy[index] +'"]';
}
}
return data_structure[position];
}
while hirarchy is the array. I get the [position] as a string which is not working well.
how can I make a js function which builds the object path dynamically by an array?
var arr = ["userconfig", "general", "name"];
var dataStructure = arr.reduceRight(function (value, key) {
var obj = {};
obj[key] = value;
return obj;
}, 'myVal');
Ends up as:
{ userconfig : { general : { name : 'myVal' } } }
Note that you may need a polyfill for the reduceRight method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
The below function will take an object to modify and an array filled with the properties needed:
function objPath(obj,path){
path.forEach(function(item){
obj[item] = {};
obj = obj[item];
});
}
var myobj = {};
objPath(myobj,["test","test2","test3"]);
console.log(myobj);
//outputs
Object {test: Object}
test: Object
test2: Object
test3: Object
The function loops over the array creating the new object property as a new object. It then puts a reference to the new object into obj so that the next property on the new object can be made.
JSFiddle
Recursive function
var array = ["userconfig", "general", "name"];
function toAssociative(array) {
var index = array.shift();
var next = null;
if (array.length > 0) {
next = toAssociative(array);
}
var result = new Array();
result[index] = next;
return result;
}

Categories