My object json is like this :
var a = [{
"attributes": {
"Code": "SGL",
"Total": "811400"
},
"DayPrice": {
"Date": "2016-07-22",
"Rate": "811400"
}
}];
I want change DayPrice to array like this :
var a = [{
"attributes": {
"Code": "SGL",
"Total": "811400"
},
"DayPrice": [{
"Date": "2016-07-22",
"Rate": "811400"
}]
}];
Any solution to solve my problem?
Thank you very much
You would need to loop through the array of objects and wrap the DayPrice property of each in an array, like this:
for (var i = 0; i < a.length; i++) {
a[i].DayPrice = [a[i].DayPrice];
}
Working example
Assign the an array with the property to the property.
a[1].DayPrice = [a[1].DayPrice];
Or use a loop:
var a = [{ "attributes": { "Code": "SGL", "Total": "811400" }, "DayPrice": { "Date": "2016-07-22", "Rate": "811400" } }];
a.forEach(function (a) {
if ('DayPrice' in a) {
a.DayPrice = [a.DayPrice];
}
});
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
Hope this will help
var a = [{
"attributes": {
"Code": "SGL",
"Total": "811400"
},
"DayPrice": {
"Date": "2016-07-22",
"Rate": "811400"
}
}];
var _getDayPrice = a[0].DayPrice;
var _dayPriceArray = [];
_dayPriceArray.push({
"Date":_getDayPrice.Date,
"Rate":_getDayPrice.Rate
})
a[0].DayPrice=_dayPriceArray;
console.log(a);
Check this jsFiddle
Related
I have an array and it looks as follow:
[
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},.....
]
How do I slice it and get only "companies": and the result as follows:
[
{
"id": 23,
"email": null,
"name": "test"
},.....
]
to clear some issues I have added the function in which I'm using data.map
fn.loadData = function (data) {
var dataKeys = Object.keys(data);
console.log(data)// 'data' is an object
console.log(data.map(x => x.companies)) ///data.map not a function error
var infiniteList = document.getElementById('infinite-list');
infiniteList.delegate = {
createItemContent: function (i) {
return ons._util.createElement(
'<ons-list-item modifier="chevron" tappable>' + data[dataKeys[i]].name + '</ons-list-item>'
);
},
countItems: function () {
return Object.keys(data).length;
}
};
infiniteList.refresh();
}
as comments told you to do:
const data = [
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},
{
"DT_RowId": "row_3758",
"companies": {
"id": 24,
"email": null,
"name": "test3"
},
"USERS": {
"UserId": 24
}
},]
console.log(data.map(obj=>obj.companies))
This worked:
const newArray = [];
for (let i = 0; i < companyArray.length; i++) {
newArray.push(companyArray[i].companies);
}
Thanks, everyone
I want to create a new array based on an original array but with merged data.
Every name key need to have merged date+time (format: YYYY-MM-DD HH:MM) with merged scores. All unique datetimes need to be available as key for each name.
ARRAY ORIGINAL:
"data": [{
"name": "A",
"history": [{
"created": "2017-05-16 00:00:00",
"score": "1"
},
{
"created": "2017-05-16 00:01:10",
"score": "1"
},
{
"created": "2017-05-16 00:01:30",
"score": "1"
}
]
},
{
"name": "B",
"history": [{
"created": "2017-05-16 00:01:00",
"score": "1"
}]
}
]
ARRAY THAT I WANT:
{
[A]: {
"2017-05-16 00:00": 1,
"2017-05-16 00:01": 2
},
[B]: {
"2017-05-16 00:00": 0,
"2017-05-16 00:01": 1
}
}
I hope you guys can help me out. I can't even think of an efficiƫnt way to do this, unfortunately. I tried to solve this issue with 5 foreach statements with no luck :(
You could use two arrays for names and times as closure and generate for all names and times a property with zero value.
var data = { data: [{ name: "A", history: [{ created: "2017-05-16 00:00:00", score: "1" }, { created: "2017-05-16 00:01:10", score: "1" }, { created: "2017-05-16 00:01:30", score: "1" }] }, { name: "B", history: [{ created: "2017-05-16 00:01:00", score: "1" }] }] },
result = data.data.reduce(function (names, times) {
return function (r, a) {
if (!r[a.name]) {
r[a.name] = {};
times.forEach(function (time) {
r[a.name][time] = 0;
});
names.push(a.name);
}
a.history.forEach(function (o) {
var time = o.created.slice(0, 16);
if (times.indexOf(time) === -1) {
names.forEach(function (name) {
r[name][time] = 0;
});
times.push(time);
}
r[a.name][time] += +o.score;
});
return r;
};
}([], []), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have to create an object not an array, As arrays cannot have a key-value pair in javascript. There is no associative array concept in javascript. You have to use objects in javascript for that.
Here is how you can do what you are trying to achieve using objects.
value = {
"data": [{
"name": "A",
"history": [{
"created": "2017-05-16 00:00:00",
"score": "1"
},
{
"created": "2017-05-16 00:01:10",
"score": "1"
},
{
"created": "2017-05-16 00:01:30",
"score": "1"
}
]},
{
"name": "B",
"history": [{
"created": "2017-05-16 00:01:00",
"score": "1"
}]
}]
};
var result ={};
value.data.forEach(function(v){
var score = {};
for(var i=0;i<v.history.length;i++){
score[v.history[i].created] = v.history[i].score;
}
result[v.name] = score;
});
console.log(result);
Now you can access data as result.A or result[A] and result.B or result[B]
SNIPPET
value = {
"data": [{
"name": "A",
"history": [{
"created": "2017-05-16 00:00:00",
"score": "1"
},
{
"created": "2017-05-16 00:01:10",
"score": "1"
},
{
"created": "2017-05-16 00:01:30",
"score": "1"
}
]
},
{
"name": "B",
"history": [{
"created": "2017-05-16 00:01:00",
"score": "1"
}]
}
]
};
var result = {};
value.data.forEach(function(v) {
var score = {};
for (var i = 0; i < v.history.length; i++) {
score[v.history[i].created] = v.history[i].score;
}
result[v.name] = score;
});
console.log(result);
I have array of objects:
var results= [
{
"_type": "MyType",
"_id": "57623535a44b8f1417740a13",
"_source": {
"info": {
"year": 2010,
"number": "string",
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}
}
];
I need to select specific fields from array. In result, I want to get the following:
[
{
"_id": "57623535a44b8f1417740a13",
"info": {
"year": 2010,
"number": "string"
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}
]
As you can see, I want to select _id field and content of _source object. How can I do this with lodash?
I've found .map function, but it doesn't take array of keys:
var res = _.map(results, "_source");
You could do:
var mapped = _.map(results, _.partialRight(_.pick, ['_id', 'info', 'type', 'date', 'createdBy']));
A little explanation:
_.map(): Expects a function which takes each item from the collection so that you can map it to something else.
_.partialRight(): Takes a function which will be called later on with the its arguments appended to the end
_.pick(): Gets the path specified from the object.
In plain Javascript you could iterate with Array#map and assemble a new object for each object without mutilation the original object.
var results = [{ "_type": "MyType", "_id": "57623535a44b8f1417740a13", "_source": { "info": { "year": 2010, "number": "string", }, "type": "stolen", "date": "2016-06-16T00:00:00", "createdBy": "57469f3c71c8bf2479d225a6" } }],
res = results.map(function (a) {
var o = { _id: a._id };
["info", "type", "date", "createdBy"].forEach(function (k) {
o[k] = a._source[k];
});
return o;
});
console.log(res);
I had the same requirement, and the below solution worked best for me.
let users = [
{
"_id": "5ead7783ed74d152f86de7b0",
"first_name": "User First name 1",
"last_name": "User Last name 1",
"email": "user1#example.com",
"phone": 9587788888
},
{
"_id": "5ead7b780d4bc43fd0ef92e7",
"first_name": "User FIRST name 1",
"last_name": "User LAST name 1",
"email": "user2#example.com",
"phone": 9587788888
}
];
users = users.map(user => _.pick(user,['_id','first_name']))
console.log(users)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
var results = [{
_type: "MyType",
_id: "57623535a44b8f1417740a13",
_source: {
info: {
year: 2010,
number: "string",
},
type: "stolen",
date: "2016-06-16T00:00:00",
createdBy: "57469f3c71c8bf2479d225a6"
}
}];
var rootProperty = ['_id']
var innerProperty = '_source'
var myArray = _.map(results, result => _(result)
.pick(rootProperty)
.assign(_.result(result, innerProperty))
.value()
)
console.log(myArray)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can map() the result and have each item assign() the _id key-value in an object toegether with the _source object.
results = _.map(results, item => _.assign(
{ _id: item._id },
item._source
));
var results = [{
"_type": "MyType",
"_id": "57623535a44b8f1417740a13",
"_source": {
"info": {
"year": 2010,
"number": "string",
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}
}];
results = _.map(results, item => _.assign(
{ _id: item._id },
item._source
));
document.write('<pre>' + JSON.stringify(results, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
You may also choose to write this in plain JS:
result = results.map(item => Object.assign(
{ _id: item._id }, item._source
));
var results = [{
"_type": "MyType",
"_id": "57623535a44b8f1417740a13",
"_source": {
"info": {
"year": 2010,
"number": "string",
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}
}];
result = results.map(item => Object.assign(
{ _id: item._id }, item._source
));
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
To correctly fulfill the OP's question and for even more complex requirements, the application of a schema and a small lodash mixin is invaluable.
The JavaScript is a little ugly, but it looks swell in CoffeeScript (yes, that was a thing once). The compiled JavaScript is hidden beneath.
_.mixin mapGet: (obj, schema) ->
result = for row in input
row_result = {}
for key, value of schema
row_result[key] = _.get(row, value)
row_result
_.mixin({ mapGet: function(obj, schema) {
var key, result, row, row_result, value;
return result = (function() {
var i, len, results;
results = [];
for (i = 0, len = input.length; i < len; i++) {
row = input[i];
row_result = {};
for (key in schema) {
value = schema[key];
row_result[key] = _.get(row, value);
}
results.push(row_result);
}
return results;
})();
}});
/* The remainer is just the proof/usage example */
var expected, input, schema;
input = [{
"_type": "MyType",
"_id": "57623535a44b8f1417740a13",
"_source": {
"info": {
"year": 2010,
"number": "string"
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}}];
expected = [{
"_id": "57623535a44b8f1417740a13",
"info": {
"year": 2010,
"number": "string"
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}];
schema = {
"_id": "_id",
"info": "_source.info",
"type": "_source.type",
"date": "_source.date",
"createdBy": "_source.createdBy"
};
console.log('expected result: ' + JSON.stringify(expected, 0, 4));
console.log('actual result: ' + JSON.stringify(_.mapGet(input, schema), 0, 4));
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
Usage:
schema = {
"_id" : "_id",
"info" : "_source.info",
"type" : "_source.type",
"date" : "_source.date",
"createdBy": "_source.createdBy",
}
_.mapGet(input, schema)
Resultant output:
[{
"_id": "57623535a44b8f1417740a13",
"info": {
"year": 2010,
"number": "string"
},
"type": "stolen",
"date": "2016-06-16T00:00:00",
"createdBy": "57469f3c71c8bf2479d225a6"
}]
Note: Complex schema can be more easily described if the source JSON is first converted to a flat, dotted, representation via:
jq [leaf_paths as $path | {"key":$path | join("."), "value":getpath($path) }] |from_entries'
$("#ELEMENT").TEXT() is giving me and html string.
<div id="ELEMENT">
{
"products": [
{
"TPNB": "52260983",
"name": "name1",
"price": 0.89,
"quantity": 1
},
{
"TPNB": "73559869",
"name": "name2",
"price": 1.1,
"quantity": 1
},
{
"TPNB": "51447540",
"name": "Tesco Dijon Mustard 185g",
"price": 0.55,
"quantity": 1
},
{
"TPNB": "61227739",
"name": "name3150ml",
"price": 0.6,
"quantity": 1
},
{
"TPNB": "56925638",
"name": "Tesco Chicken Thighs 1kg",
"price": 2.5,
"quantity": 2
}
]
}
</div>
I want to extract this Array into following index
"TPNB":"52260983","name":"name1","price":0.89,"quantity":1
"TPNB":"52260983","name":"name2","price":0.89,"quantity":1
"TPNB":"56925638","name":"name13","price":2.5,"quantity":2
var parsedJson = JSON.parse($("#ELEMENT").text())
var finalArray = new Array()
for (var i in parsedJson.products)
{
finalArray.push(parsedJson.products[i]);
}
for (var i in finalArray)
{
console.log(JSON.stringify(finalArray[i]).replace("{", "").replace("}", ""))
}
after this you can access properties as such
finalArray[0].TPNB
finalArray[0].name
finalArray[0].price
finalArray[0].quantity
for the full code open you browser console and check out this http://jsfiddle.net/5wd29qch/1/
If the text is a valid json, you can parse it and get the products property which is the array you want:
var raw = $("#ELEMENT").text(),
parsed = JSON.parse(raw),
products = parsed.products;
console.log(products);
console.log(products[0]);
console.log(products[1]);
console.log(products[2]);
var jsonData = // ur data from .text()
var productData = JSON.parse(jsonData);
var productRows = productData.products;
for(var i = 0; i < productRows.length; i++)
{
alert(productRows[i]);
}
Try this:
var json = $.parseJSON($('#ELEMENT').text());
json.products.map(function(v, i){
console.log(JSON.stringify(v).replace('{','').replace('}',''));
});
Output:
"TPNB":"52260983","name":"name1","price":0.89,"quantity":1
"TPNB":"73559869","name":"name2","price":1.1,"quantity":1
"TPNB":"51447540","name":"Tesco Dijon Mustard 185g","price":0.55,"quantity":1
"TPNB":"61227739","name":"name3150ml","price":0.6,"quantity":1
"TPNB":"56925638","name":"Tesco Chicken Thighs 1kg","price":2.5,"quantity":2
From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{ "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" },
{ "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" },
{ "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" }
]
}
I tried out the code below but it doesn't work - it either says:
is null
not an object
length is null
r not an object
var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++)
startyear += rss[i].startyear
Use
for (i = 0; i < 3; i++) {
alert(JSON.infos.info[0].note.notes[i].title);
}
TRY IT HERE: JSFIDDLE WORKING EXAMPLE
BTW your JSON is not valid. Use this JSON:
var JSON = {
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
EDIT:
Here is what you want:
var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) {
var notesLength= JSON.infos.info[infoIndex].note.notes.length;
for (noteIndex = 0; noteIndex < notesLength; noteIndex++) {
alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title);
}
}
Putting your json into an var called obj, use the following:
obj.infos.info[0].note.notes[0].title
http://jsfiddle.net/Znq34/
Well the "path" to the JSON notes array-like object is:
json.infos.info[0].note.notes;
So you could do something like:
var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{
titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));
Fiddle: http://jsfiddle.net/garreh/uDxqD/
Are you using jQuery? ;-)
// Assuming your using "success" in ajax response
success: function(json)
{
var titles = $(json.infos.info[0].note.notes).map(function() {
return this.title;
}).get();
alert(titles.join(', '));
}
First count the length of notes
var len = jsonobject.infos.info.note.notes.length;
Then loops through and get
var title = jsonobject.infos.info.note.notes[i].title;