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);
}
Related
I have an array of objects like this:
[
{ "key": "fruit", "value": "apple" },
{ "key": "color", "value": "red" },
{ "key": "location", "value": "garden" }
]
I need to convert it to the following format:
[
{ "fruit": "apple" },
{ "color": "red" },
{ "location": "garden" }
]
How can this be done using JavaScript?
You can use .map
var data = [
{"key":"fruit","value":"apple"},
{"key":"color","value":"red"},
{"key":"location","value":"garden"}
];
var result = data.map(function (e) {
var element = {};
element[e.key] = e.value;
return element;
});
console.log(result);
also if you use ES2015 you can do it like this
var result = data.map((e) => {
return {[e.key]: e.value};
});
Example
Using an arrow function, with the data called arr
arr.map(e => {
var o = {};
o[e.key] = e.value;
return o;
});
This generates a new Array and does not modify the original
It can be simplified down to one line as
arr.map(e => ({[e.key]: e.value}));
If you can't assume arrow function support yet, you would write this longhand
arr.map(function (e) {
var o = {};
o[e.key] = e.value;
return o;
});
Using map (as suggested in other answers) or the following will do what you want...
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
var obj = {};
for(var i = 0; i < data.length; i++) {
obj[data[i]["key"]] = data[i]["value"];
}
In Javascript, obj.property and obj['property'] return same things.
obj['property'] is more flexible because the key 'property' could be a string with some space :
obj['pro per ty'] // work
obj.pro per ty // not work
or
var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true
So you could try that.
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];
var data_length = data.length; // just a little optimisation for-loop
for (var i = 0; i < data_length; i++) {
var item = data[i]; // to have a vision close of foreach-loop (foreach item of collection)
new_data[i] = {};
new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]
What you currently have is an array of object, each having two attributes, key and value. If you are not aware of map, you can always run a forEach loop on this array and rearrange the data. Try something like below:
function() {
var newArray = [];
oldArray.forEach(function(x){
var obj= {};
obj[x.key] = x.value;
newArray.push(obj);
});
console.log(newArray);
}
here oldArray is your original data
I have a JS object:
var source = {};
source.quantity = 1;
source.text = 'test';
Now I JSON it:
var json = JSON.stringify(source);
json looks like this:
{"quantity":"1","text":"test"}
I would like it to be like this:
[{"quantity":"1"},{"text":"test"}]
Ho can I do this?
Get all the keys as an Array them map them to Objects as key-value pairs from source
JSON.stringify(
Object.keys(source)
.map(
function (e) {
var o = {};
o[e] = source[e];
return o;
}
)
); // "[{"quantity":1},{"text":"test"}]"
var json = JSON.stringify([
{quantity: "1"},
{text: "test"}
]);
I guess this is not possible but you can do this:
var source = {};
source.quantity = 1;
source.text = 'test';
var result = [];
for(var i in source) {
var obj = {};
obj[i] = source[i];
result.push(obj);
}
var json = JSON.stringify(result);
I hope this can help you.
I have JSON object returned from elastic search like below, I am able to get the data using this,
$scope.results = response.hits.hits;
console.log($scope.results);
var resultstofilter = [];
var resultArray = [];
for (var i=0; i<$scope.results.length; ++i) {
var result = $scope.results[i];
resultstofilter[i] = {};
for (var key in result) {
if (key === '_source' || key === 'Calls') {
var Oriobj = result[key];
resultArray.push(Oriobj);
console.log(resultArray);
$scope.resultData = resultArray;
}
}
}
for(var key in $scope.resultData) {
}
});
Result:
I need to get the fields of an index. Say in this sample.
Agent
Calls
Is there a way i can directly get the value of key like we do in c#.Something like this,
$scope.resultData["key"];
There are many ways. One of them is to use underscore _.pluck
var getIndex = _.pluck($scope.resultData,'_index');
Or:
$scope.resultData.filter(function(myObject) {
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
$scope.fieldsOfIndex.push(prop);
}
}
});
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;
}
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);