I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.
Related
I'm trying to convert url. Using for loop to extract Acura, Audi. Here what I got so far:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
console.log(makes)
}
};
The result is
[ 'Acura' ]
[ 'Acura', 'Audi' ]
As you see it has one more array. Is there a way to get only [ 'Acura', 'Audi' ]?
FYI there's a native solution for getting values a from query string, check URLSearchParams
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const makes = new URLSearchParams(newSrpParams).getAll('make');
console.log(makes);
That is happening because you are logging the array inside the for loop. If you move it outside you will get
['Acura', 'Audi']
The Code:
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
console.log(newSrpParamsArray)
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
console.log(make)
makes.push(make);
}
};
console.log(makes) // The change
You were consoling the results inside the if statement it will run two times. So as a result make[] array print two times. That's why you get the two arrays.
var newSrpParams = 'year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000';
const newSrpParamsArray = newSrpParams.split("&");
var oldSrpParams;
var makes = [];
for(var i = 0 ; i < newSrpParamsArray.length; i++){
if(newSrpParamsArray[i].includes('make')) {
const make = newSrpParamsArray[i].replace('make=','')
makes.push(make);
}
};
console.log(makes)
Make sure to console make[] from outside of the for a loop. That's only. I couldn't see any other wrong line in your code.
Why not use URLSearchParams?
and you can replace the URL with window.location.href
let url = new URL(`http://localhost?year=2020-2022&make=Acura&make=Audi&model=A3&model=A5&trim=2.0T%20Premium&trim=2.0T%20S%20line%20Premium&normalBodyStyle=Hatchback&normalBodyStyle=Sedan&odometer=13000-38000&internetPrice=20000-50000`)
let params = new URLSearchParams(url.search).getAll("make")
console.log(params)
I have an array barcodeList that stores different barcode numbers. I want to make every single one of them into a different object with the key being the barcode numbers and having different properties. Then I want to put them all into one big object foodItems. How can I do this.
Also, I realized that numbers can't be used to make variables, so I would want to put a keyword in front of them. Also, the image and ingredient values of null are just placeholders for now.
Wanted Result -
foodItems = {
Data9001: {
image : null
ingredients : null
}
Data9002: {
image : null
ingredients : null
}
}
From barcodeList = [9001, 9002]
Any recommends methods to user or keywords would be appreciated as well.
Attempted:
barcodeList.push(code)
var Food = function() {
this.image = "noImage.png"
this.nutrients = null
this.ingredients = null
}
var foodItems = {}
for (var i in barcodeList) {
//Some append function
var something = new Food()
}
To use the bracket notation to create the keys
var barcodeList = [9001, 9002];
var foodItems = {};
barcodeList.forEach(function(item){
foodItems['Data'+item] = {
image : null,
ingredients : null
};
});
console.log(foodItems);
First of all, I didn't understand, what do you mean by this
I realized that numbers can't be used to make variables
but as per your requirement, you can do something like this
var barcodeList = [9001,9002];
var foodItems = {};
for (var i = 0; i < barcodeList.length; i++) {
foodItems[barcodeList[i]] = {
image : null,
ingredients : null
}
}
console.log(foodItems)
Edited:
As per your code you can do this
var barcodeList = [9001, 9002]
var foodItems = {};
var Food = function() {
this.image = "noImage.png"
this.nutrients = null
this.ingredients = null
}
var foodItems = {}
for (var i = 0; i < barcodeList.length; i++) {
var something = new Food()
foodItems[barcodeList[i]] = something;
}
console.log(foodItems);
Not sure, how far you have gone with your answer. I would use
the Array.prototype.map() to create an array of Data objects and then use the reduce to concatenate.
Few pointers
As you need keys to begin with Data I would use ['Data'+barcode] to create them.
I will also use the ES6 spread operator to concatenate.
Here is the working code.
"use strict"
var barcodeList = [9001, 9002];
var result = barcodeList.map(function(barcode){
return {
['Data'+barcode]: {
image: null,
ingredients : null
}
}
}).reduce(function(prevValue,currValue){
return {...prevValue, ...currValue};
});
console.log ( result);
I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}
I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}
This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}