I have this JSON:
var person = {"id": "1", "name": "Michel"}
How would I return "1" when "Michel" is selected.
I have tried:
for (value in person) {
if (person.hasOwnProperty(value)) {
console.log(value+ " = " + person[value]);
}
}
You mean like this?
var person = [{"id": "1", "name": "Michel"}];
for(index=0;index<person.length;index++) {
if(person[index].name == 'Michel') {
console.log(person[index].id);
}
}
Another Way
var person = [{"id": "1", "name": "Michel"}];
var string = 'Michel';
function searchArray(str) {
var id = '';
for(index=0; index<person.length; index++) {
if(person[index].name == str) {
id = person[index].id;
}
}
return id;
}
var result_id = searchArray(string);
Related
Before
This is an object with multiple rows:
{
"functions": [
{
"package_id": "2",
"module_id": "2",
"data_id": "2"
},
{
"package_id": "1",
"module_id": "1",
"data_id": "2"
},
{
"package_id": "2",
"module_id": "3",
"data_id": "3"
}
]
}
Desired result
I want this to return into a "nested" Object like below, without duplicates:
{
"packages": [
{
"package_id": "2",
"modules": [
{
"module_id": "2",
"data": [
{
"data_id": "2"
}
]
},
{
"module_id": "3",
"data": [
{
"data_id": "3"
}
]
}
]
},{
"package_id": "1",
"modules": [
{
"module_id": "1",
"data": [
{
"data_id": "2"
}
]
}
]
}
]
}
I've already tried loops inside loops, with constructing multiple arrays and objects. Which causes duplicates or overriding objects into single ones. Is there a more generic way to generate this with JavaScript? (It's for an Angular (6) project.
Example 1
getFunctionPackage() {
var fList = this.functionList;
var dArr = [];
var dObj = {};
var pArr = [];
var pObj = {};
var mArr = [];
var mObj = {};
for (var key in fList) {
pObj['package_id'] = fList[key]['package_id'];
mObj['module_id'] = fList[key]['module_id'];
dObj['data_id'] = fList[key]['data_id'];
for (var i = 0; i < pArr.length; i++) {
if (pArr[i].package_id != pObj['package_id']) {
pArr.push(pObj);
}
for (var x = 0; x < mArr.length; x++) {
if (pArr[i]['modules'][x].module_id != mObj['module_id']) {
mArr.push(mObj);
}
for (var y = 0; y < dArr.length; y++) {
if (pArr[i]['modules'][x]['datas'][y].data_id != dObj['data_id']) {
dArr.push(dObj);
}
}
}
}
if (dArr.length == 0) {
dArr.push(dObj);
}
mObj['datas'] = dArr;
if (mArr.length == 0) {
mArr.push(mObj);
}
pObj['modules'] = mArr;
if (pArr.length == 0) {
pArr.push(pObj);
}
dObj = {};
mObj = {};
pObj = {};
}
}
Example 2:
Results in skipping cause of the booleans
var fList = this.functionList;
var dArr = [];
var dObj = {};
var pArr = [];
var pObj = {};
var mArr = [];
var mObj = {};
var rObj = {};
for (var key in fList) {
pObj['package_id'] = fList[key]['package_id'];
mObj['module_id'] = fList[key]['module_id'];
dObj['data_id'] = fList[key]['data_id'];
var pfound = false;
var mfound = false;
var dfound = false;
for (var i = 0; i < pArr.length; i++) {
if (pArr[i].package_id == pObj['package_id']) {
for (var x = 0; x < mArr.length; x++) {
if (pArr[i]['modules'][x].module_id == mObj['module_id']) {
for (var y = 0; y < dArr.length; y++) {
if (pArr[i]['modules'][x]['datas'][y].data_id == dObj['data_id']) {
dfound = true;
break;
}
}
mfound = true;
break;
}
}
pfound = true;
break;
}
}
if (!dfound) {
dArr.push(dObj);
mObj['datas'] = dArr;
dObj = {};
}
if (!mfound) {
mArr.push(mObj);
pObj['modules'] = mArr;
mObj = {};
}
if (!pfound) {
pArr.push(pObj);
pObj = {};
}
dArr = [];
mArr = [];
}
rObj['packages'] = pArr;
console.log(rObj);
Here's a more generic approach using Array#reduce() to create a grouped object based on the package id as keys. You can use any loop to build this same object ...for() or forEach() for example.
Then use Object.values() to get the final array from that grouped object
Using methods like Array#find() simplifies traversing to see if a module exists already or not within each package
const grouped = data.functions.reduce((a, c )=>{
// if group object doesn't exist - create it or use existing one
a[c.package_id] = a[c.package_id] || {package_id : c.package_id, modules: [] }
// store reference to the group modules array
const mods = a[c.package_id].modules
// look within that group modules array to see if module object exists
let module = mods.find(mod => mod.module_id === c.module_id)
if(!module){
// or create new module object
module = {module_id: c.module_id, data:[]}
// and push it into modules array
mods.push(module);
}
// push new data object to module data array
module.data.push({data_id: c.data_id})
return a
}, {})
// create final results object
const res = { packages : Object.values(grouped) }
console.log(res)
.as-console-wrapper {max-height: 100%!important;}
<script>
const data = {
"functions": [{
"package_id": "2",
"module_id": "2",
"data_id": "2"
},
{
"package_id": "1",
"module_id": "1",
"data_id": "2"
},
{
"package_id": "2",
"module_id": "3",
"data_id": "3"
}
]
}
</script>
I have bellow mentioned of dynamic js object form which I try to convert it to Schema Data and add into head tag of the web page for SEO purpose.
Not sure how it can be possible as I am new staff on this.
My JS Function:
function populateJsonLDScript(data) {
if (typeof (data) != "undefined" && data != null) {
var finalSchemaObj = {};
var tempSchemaItems = [];
for (var i = 0; i < data.length; i++) {
var tempSchemaData = {};
tempSchemaData["#type"] = "ListItem";
tempSchemaData["position"] = data[i].DisplayOrder;
tempSchemaData["item"] = {
"#id": data[i].CanonicalURL,
"name": data[i].Name
};
tempSchemaItems.push(tempSchemaData);
}
for (var i = 0; i < tempSchemaItems.length; ++i) {
finalSchemaObj[i] = tempSchemaItems[i];
}
var scriptSchema = document.createElement('script');
scriptSchema.type = 'application/ld+json';
scriptSchema.text = JSON.stringify({
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": [finalSchemaObj]
});
if ($('head script[type="application/ld+json"]').length > 0) {
$('head script[type="application/ld+json"]').remove();
$("head").append(scriptSchema);
} else {
$("head").append(scriptSchema);
}
}
}
OUTPUT
{
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": [{
"0": {
"#type": "ListItem",
"position": 0,
"item": {
"#id": "http://example.com",
"name": "Home"
}
},
"1": {
"#type": "ListItem",
"position": 1,
"item": {
"#id": "http://example.com/jewelry",
"name": "Jewelry"
}
},
"2": {
"#type": "ListItem",
"position": 2,
"item": {
"#id": "http://example.com/jewelry/necklaces-pendants",
"name": "Necklaces & Pendants"
}
}
}]
}
But Still Google said its invalid format. So, I want to format the above to -
{"#context":"http://schema.org","#type":"BreadcrumbList","itemListElement":[
{
"#type":"ListItem",
"position":0,
"item": {
"#id":"http://example.com",
"name":"Home"
}
},
{
"#type":"ListItem",
"position":1,
"item":{
"#id":"http://example.com/jewelry",
"name":"Jewelry"
}
},
{
"#type":"ListItem",
"position":2,
"item":{
"#id":"http://example.com/jewelry/necklaces-pendants",
"name":"Necklaces & Pendants"
}
}
]
}
Anyone please help how to do this?
Don't use object, use array and push into it. Something like this:
function populateJsonLDScript(data) {
if (typeof(data) != "undefined" && data != null) {
var finalSchemaObj = []; // <----- use array here
var tempSchemaItems = [];
for (var i = 0; i < data.length; i++) {
var tempSchemaData = {};
tempSchemaData["#type"] = "ListItem";
tempSchemaData["position"] = data[i].DisplayOrder;
tempSchemaData["item"] = {
"#id": data[i].CanonicalURL,
"name": data[i].Name
};
tempSchemaItems.push(tempSchemaData);
}
for (var i = 0; i < tempSchemaItems.length; ++i) {
finalSchemaObj.push(tempSchemaItems[i]); // <--- push here
}
var scriptSchema = document.createElement('script');
scriptSchema.type = 'application/ld+json';
scriptSchema.text = JSON.stringify({
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": finalSchemaObj // <----- and use finalSchemaObj here
});
if ($('head script[type="application/ld+json"]').length > 0) {
$('head script[type="application/ld+json"]').remove();
$("head").append(scriptSchema);
} else {
$("head").append(scriptSchema);
}
}
}
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'];
....
}
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);
I have a JSON data structure as shown below:
{
"name": "World",
"children": [
{ "name": "US",
"children": [
{ "name": "CA" },
{ "name": "NJ" }
]
},
{ "name": "INDIA",
"children": [
{ "name": "OR" },
{ "name": "TN" },
{ "name": "AP" }
]
}
]
};
I need to change the key names from "name" & "children" to say "key" & "value". Any suggestion on how to do that for each key name in this nested structure?
I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.
var parsed = JSON.parse(myJSONData, function(k, v) {
if (k === "name")
this.key = v;
else if (k === "children")
this.value = v;
else
return v;
});
DEMO: http://jsfiddle.net/BeSad/
Try this:
function convert(data){
return {
key: data.name,
value: data.children.map(convert);
};
}
Or if you need to support older browsers without map:
function convert(data){
var children = [];
for (var i = 0, len = data.children.length; i < len; i++){
children.push(convert(data.children[i]));
}
return {
key: data.name,
value: children
};
}
You could use a function like this :
function clonerename(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
var newPropName = prop;
if (prop=='name') newPropName='key';
else if (prop=='children') newPropName='value';
clone[newPropName] = clonerename(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = clonerename(A);
Note that what you have isn't a JSON data structure (this doesn't exist as JSON is a data-exchange format) but probably an object you got from a JSON string.