javascript object manipulation using loop - javascript

[{
"name":"John"
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
John have 2 hobbies, it suppose to be in array but I have no control of the source of the api. How can I make the json to be below format?
[{
"name":"John"
"age":19,
"hobby":"Basketball"
},{
"name":"John"
"age":19,
"hobby":"play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
I'm new to jquery so here's code I've tried :
var hobbies = "";
$.each(json, function(){
hobbies = this.hobby.split(',');
});

var data = [{
"name": "John",
"age": 19,
"hobby": "Basketball;play computer"
}, {
"name": "Anderson",
"age": 19,
"hobby": "Tennis"
}]
$.each(data, function (index, value) {
if (value.hobby.split(';').length > 1) {
var dataArray = value.hobby.split(';');
value.hobby = dataArray[0];
dataArray.shift();
$.each(dataArray, function (innerIndex, innerValue) {
data.push({
"name": value.name,
"age": value.age,
"hobby": innerValue
});
});
}
});
console.log(data);
Fiddle Demo

var arr = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$.each(arr, function(i,j){
var temp = j.hobby;
var hobby_arr = temp.split(';');
j.hobby = hobby_arr;
});
Try this. However there is an error in your provided json. There should be a ',' after the 'name' value

Here is a fiddle of your working thing ( assuming that ";" is the separator )
http://jsfiddle.net/swaprks/vcpq8dtr/
var json = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$(function(){
for ( var i = 0; i < json.length; i++ ) {
var obj = json[i];
if ( obj["hobby"].indexOf(";") != -1 ){
var hobbyArr = obj["hobby"].split(";");
for ( var j = 0; j < hobbyArr.length; j++ ){
var newObj = {};
if ( j == 0 ){
json[i]["hobby"] = hobbyArr[j];
} else {
newObj = {
"name": obj["name"],
"age": obj["age"],
"hobby": hobbyArr[j]
}
json.push(newObj);
}
}
}
}
console.log(json)
});

Related

how to add an element inside a json array at the specific index in a repeating block?

I am trying to add element "delete:true" after each occurrence of "_rev " mentioned in the below sample request.
Original Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
Expected Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
"_deleted" :true
},
{
"_id": "456",
"_rev": "1-1192",
"_deleted" :true
}
]
}
When I tried the below code,the ""_deleted" :true" is getting inserted after the -rev element is closed. PFB for the same and suggest.
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
for (var value in params.docs[i]) {
if(value == '_rev' && params.docs[i]._rev ){
var string1 = JSON.stringify(params.docs[i]);
var str = ',';
var string2 = '"';
var string3 =str+string2+ '_deleted'+ string2+ ':' + "true" ;
var res = string1 + string3 ;
}
}
}
}
######################
[
"2018-01-23T09:44:23.568738362Z stdout:
{\"_id\":\"123\",
\"_rev\":\"1-7836\"},
\"_deleted\":true"]
Use map and Object.assign instead of generating a string
var output = params.docs.map( s => Object.assign( {}, {"_deleted" :true}, s ) );
You can then convert this to string using JSON.stringify( output );
Demo
var params = {
"docs": [{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
};
var output = params.docs.map(s => Object.assign({}, {
"_deleted": true
}, s));
console.log(output);
var data = {
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
var newData = data['docs'].map(item => {
item._delete = true
return item
})
console.log(newData);
Why don't you simply put ._deleted attribute to doc, like this ?
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]._deleted = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
Or like this :
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]["_deleted"] = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
You can reference the not existing attribute directly and assign an value:
#!/usr/bin/js
var myJSON = { "docs": [ { "_id":"123", "_rev":"1-200" } ] }
console.log(myJSON);
myJSON.docs[0]["_deleted"]=true;
console.log(myJSON);
Output of example:
# js append.js
{ docs: [ { _id: '123', _rev: '1-200' } ] }
{ docs: [ { _id: '123', _rev: '1-200', _deleted: true } ] }
Read the more extensive example here: Add new attribute (element) to JSON object using JavaScript
So this might be a duplicate ...

Push Unique Objects to JavaScript Array

How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}

loop through json javascript

I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);

Recursively recombining split key/values pairs

This is making my head hurt, if there are any generous javascript gurus here, i would greatly appreciate some help
What I'm trying to achieve is this:
Given this:
var keys = ["Age", "Name", "Photos", { "Friends": ["FirstName", "LastName"] }];
var values = [ [31, "Bob", ["1.jpg", "2.jpg"], [ ["Bob", "Hope"], ["Foo", "Bar"] ] ], [21, "Jane"] ["4.jpg", "5.jpg"], [ ["Mr", "T"],["Foo", "Bar"] ] ];
I would like to get back this:
var object = [
{
"Age" : 31,
"Name" : "Bob",
"Photos" : ["1.jpg", "2.jpg"]
"Friends": [
{
"FirstName": "Bob",
"LastName" : "Hope"
},
{
"FirstName": "Foo",
"LastName" : "Bar"
}
]
},
{
"Age" : 21,
"Name" : "Jane",
"Photos" : ["4.jpg", "5.jpg"]
"Friends": [
{
"FirstName": "Mr",
"LastName" : "T"
},
{
"FirstName": "Foo",
"LastName" : "Bar"
}
]
}
];
It's for a spec proposal (JsonR) i'm working on here
Currently i'm able to (almost) work this out (but not any deeper..):
var keys = ["Age", "Name", "Photos" ];
var values = [ [31, "Bob", ["1.jpg", "2.jpg"]], [21, "Jane", ["4.jpg", "5.jpg"]] ];
Thank's for any feedback or help!
Here's a function that does what I think you want:
function keyValuesToObject(keys, values) {
var obj = [];
for (var i = 0; i < values.length; i++) {
var value = values[i];
obj.push({});
for (var j = 0; j < value.length; j++) {
var key = keys[j];
if (typeof key === "object") {
for (var k in key) {
obj[i][k] = keyValuesToObject(key[k], value[j]);
}
}
else {
obj[i][key] = value[j];
}
}
}
return obj;
};
It does not handle malformed input, so you might want to put checks in there depending on how you plan to use it.
You can see it in action on this online jsFiddle demo.
By the way, the key and value value arrays you gave had mismatched opening and closing brackets, so I had to fix them.
Fiddle
function pairUpItem(keys, values) {
var len = keys.length;
var result = {};
for (var i = 0; i < len; i++) {
var key = keys[i];
var value = values[i];
if (typeof(key) == "string") {
result[key] = value;
} else {
for (var key2 in key) {
if (key.hasOwnProperty(key2)) {
result[key2] = pairUpItems(key[key2], value);
}
}
}
}
return result;
}
function pairUpItems(keys, values) {
var len = values.length;
var result = [];
for (var i = 0; i < len; i++) {
var value = values[i];
if (typeof(value) !== "undefined") {
result.push(pairUpItem(keys, value));
}
}
return result;
}
var keys = ["Age", "Name", "Photos", { "Friends": ["FirstName", "LastName"] }];
var values = [ [31, "Bob", ["1.jpg", "2.jpg"], [ ["Bob", "Hope"], ["Foo", "Bar"] ] ], [21, "Jane", ["4.jpg", "5.jpg"], [ ["Mr", "T"],["Foo", "Bar"] ] ] ];
var result = pairUpItems(keys, values);
​console.dir(result);​

JSON to filtered Array in JavaScript

I have this JSON string:
[
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
]
And I need to produce a filtered array without repeated PK, in the example above the last entry: "pk": "alpha","anotherkey": { ... should be eliminated from the output array. All this using JavaScript. I tried with the object JSON.parse but it returns many key,value pairs that are hard to filter for example "key=2 value=[object Object]".
Any help is greatly appreciated.
var data = JSON.parse(jsonString);
var usedPKs = [];
var newData = [];
for (var i = 0; i < data.length; i++) {
if (usedPKs.indexOf(data[i].pk) == -1) {
usedPKs.push(data[i].pk);
newData.push(data[i]);
}
}
// newData will now contain your desired result
var contents = JSON.parse("your json string");
var cache = {},
results = [],
content, pk;
for(var i = 0, len = contents.length; i < len; i++){
content = contens[i];
pk = content.pk;
if( !cache.hasOwnPropery(pk) ){
results.push(content);
cache[pk] = true;
}
}
// restuls
<script type="text/javascript">
// Your sample data
var dataStore = [
{
"pk": "alpha",
"item": [{
"child": "val"
}]
},
{
"pk": "beta",
"attr": "val",
"attr2": [
"child1"
]
},
{
"pk": "alpha",
"anotherkey": {
"tag": "name"
}
}
];
// Helper to check if an array contains a value
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
// temp array, used to store the values for your needle (the value of pk)
var tmp = [];
// array storing the keys of your filtered objects.
var filteredKeys = [];
// traversing you data
for (var i=0; i < dataStore.length; i++) {
var item = dataStore[i];
// if there is an item with the same pk value, don't do anything and continue the loop
if (tmp.contains(item.pk) === true) {
continue;
}
// add items to both arrays
tmp.push(item.pk);
filteredKeys.push(i);
}
// results in keys 0 and 1
console.log(filteredKeys);
</script>

Categories