Accessing data in JS structure - javascript

I'm trying to parse the following data:
data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
Using this data I want to iterate through each object and return its ID, and then all of it options.
I know I need to use for loop like this:
for (var i =0; i < data.length; i++) {
var id = data[i].id;
var optionText = data[i].options[i].text;
var optionValue = data[i].options[i].value;
console.log(id);
console.log(optionText);
console.log(optionValue);
}:
This loop only returns the first OptionText & OptionValue from the data. Can you teach me what I'm doing wrong?
Thanks.

You could use another for loop for the inner array.
var data = [{ "id": "orderBy", "options": [{ "value": "order-by=newest&", "name": "newest" }, { "value": "order-by=relevance&", "name": "relevance" }] }, { "id": "searchBy", "options": [{ "value": "search-by=name&", "name": "name" }, { "value": "search-by=number&", "name": "number" }, { "value": "search-by=date&", "name": "date" }, { "value": "search-by=location&", "name": "location" }] }],
i, j, id, optionText, optionValue;
for (i = 0; i < data.length; i++) {
id = data[i].id;
for (j = 0; j < data[i].options.length; j++) {
optionText = data[i].options[j].name;
optionValue = data[i].options[j].value;
console.log(id, optionText, optionValue);
}
}

data = [
{"id":"orderBy", "options" : [
{"value":"order-by=newest&", "name":"newest"},
{"value":"order-by=relevance&", "name":"relevance"}
]},
{"id":"searchBy", "options" : [
{"value":"search-by=name&", "name":"name"},
{"value":"search-by=number&", "name":"number"},
{"value":"search-by=date&", "name":"date"},
{"value":"search-by=location&", "name":"location"}
]}
];
for (var i in data) {
var id = data[i].id;
console.log(id)
for (var opt of data[i].options){
console.log(opt.value);
console.log(opt.name)
}
}
You lacked an interation loop. Also I believe it could be the perfect example for you to see the difference (and existence?) of iterating through objects and arrays with in and of

You have two levels of arrays you need to loop through. First loop through the outer array, and then through the options of each item:
var data = [{"id":"orderBy","options":[{"value":"order-by=newest&","name":"newest"},{"value":"order-by=relevance&","name":"relevance"}]},{"id":"searchBy","options":[{"value":"search-by=name&","name":"name"},{"value":"search-by=number&","name":"number"},{"value":"search-by=date&","name":"date"},{"value":"search-by=location&","name":"location"}]}];
for (var i = 0; i < data.length; i++) {
var id = data[i].id;
console.log(id);
for(var j = 0; j < data[i].options.length; j++) {
var optionText = data[i].options[j].name;
var optionValue = data[i].options[j].value;
console.log(optionText);
console.log(optionValue);
}
}

Related

Json - create an ID column that auto increment

I'm building a json object from 2 dataset and I need to add a column (ID) with a unique value,
I have thought that having an auto increment ID (1,2,3,4..) value will be great
This is how I'm building my Json object with JavaScript
var output = [];
for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
var row = {};
for (var fieldIdx =0; fieldIdx < fields.length; fieldIdx++) {
var field = editor.field( fields[fieldIdx] );
var mapped = data[ field.name() ];
row[field.name()] = csv[rowIdx][mapped];
}
output.push(row);
}
var json = JSON.stringify(output);
console.log(json)
and this is my JSON: PLEASE NOTE: I want to add "id": "1" column whose value will auto increment for each record
[
{
"id": "1", <--- DESIRED
"title": "Hello World",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www"
]
},
{
"id": "2", <--- DESIRED
"title": "Lorem Ipsum",
"artist": "John Smith",
"genre": "pop",
"week": "4",
"highest_rating": "3",
"year": "2014",
"youtube": "www"
]
}
]
you can do this row.id = (rowIdx + 1);
var output = [];
for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
var row = {};
for (var fieldIdx = 0; fieldIdx < fields.length; fieldIdx++) {
var field = editor.field(fields[fieldIdx]);
var mapped = data[field.name()];
row[field.name()] = csv[rowIdx][mapped];
}
row.id = (rowIdx + 1); // <--- this line
output.push(row);
}
var json = JSON.stringify(output);
console.log(json);
You can increment an i number starting from 0, for Id of each object in the output array. For example:
for(let i=0; i<output.length; i++)
{ output[i].id=i+1;}

how do not push all the array not have this product

for example i have this code i used this json:
"food": {
"appetizers": [
{
"id": 1,
"image": "../image/calammari.png",
"title": "rings",
"price": 11500,
"ingredient":[{
"id" : "0001",
"name": "avocado"
},
{
"id" : "0001",
"name": "tomato"
}
]
},
{
"id": 2,
"image": "../image/food2.png",
"title": "bang bang",
"price": 10000,
"ingredient":[{
"id" : "0001",
"name": "eggplant"
},
{
"id" : "0001",
"name": "cucumber"
}
]
}
from this json file if the array my access equal tomato , just i want to display the food that have tomato.
so i used this html:
<div ng-repeat="appetizer in appetizers ">
<div>
<img ng-src="{{appetizer.image}}" />
<div >
<p >
{{appetizer.title | uppercase}}
</p>
</div>
and this javascript :
var myAccess = ["tomato"];
$scope.test = [];
var appetizer = $scope.appetizers;
for (var i = 0; i < $scope.appetizers.length; i++) {
for (var j = 0; j < $scope.appetizers[i].ingredient.length; j++) {
if ($scope.appetizers[i].ingredient[j].name === myAccess) {
// what should i write here
}
}
}
return null; }
sorry its about this if someone can help please !!
so myAccess = tomato , and should read the first of the appetizer that in the ingredient tomato , and i want to push just the ingredient that have tomato .
You can use filter and some or every in the following way:
Items that have some of the ingredients
const data = [{"id":1,"image":"../image/calammari.png","title":"rings","price":11500,"ingredient":[{"id":"0001","name":"avocado"},{"id":"0001","name":"tomato"}]},{"id":2,"image":"../image/food2.png","title":"bang bang","price":10000,"ingredient":[{"id":"0001","name":"eggplant"},{"id":"0001","name":"cucumber"}]}];
const myAccess = ['avocado', 'tomato'];
console.log(
data.filter(
(item) =>
item.ingredient.some(
(ingredient) => myAccess.includes(ingredient.name)
)
)
);
Items that have all of the ingredients:
data.filter(
(item) =>
myAccess.every(
(ingredient)=>
item.ingredient.some(
(i)=>i.name===ingredient
)
)
);
it could be helpful for you
var app=angular.module("myapp",[]);
app.controller("test_ctrl",function($scope){
$scope.appetizers = [];
$scope.temp={
"food": {
"appetizers": [
{
"id": 1,
"image": "../image/calammari.png",
"title": "rings",
"price": 11500,
"ingredient":[
{
"id" : "0001",
"name": "avocado"
},
{
"id" : "0001",
"name": "tomato"
}
]
},
{
"id": 2,
"image": "../image/food2.png",
"title": "bang bang",
"price": 10000,
"ingredient":[
{
"id" : "0001",
"name": "eggplant"
},
{
"id" : "0001",
"name": "cucumber"
}
]
}
]
}
}
var myAccess = ["tomato"];
var appetizer = $scope.temp.food.appetizers;
for (var i = 0; i < appetizer.length; i++) {
for (var j = 0; j < appetizer[i].ingredient.length; j++) {
if (appetizer[i].ingredient[j].name === myAccess[0]) {
$scope.appetizers.push(appetizer[i]);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myapp" ng-controller="test_ctrl">
<div ng-repeat="appetizer in appetizers ">
<div>
<img ng-src="{{appetizer.image}}" />
<div >
<p >
{{appetizer.title | uppercase}}
</p>
</div>
</div>
</div>
In addition to the comment, check the below JS that might sort out your problem.
function myFunction() {
var myAccess = "tomato";
$scope.test = [];
var appetizer = $scope.appetizers;
for (var i = 0; i < $scope.appetizers.length; i++) {
var flag = 'false';
for (var j = 0; j < $scope.appetizers[i].ingredient.length; j++) {
if ($scope.appetizers[i].ingredient[j].name === myAccess) {
flag = 'true'; // Flag to check whether it's exist
break;
}
}
if(flag == 'false') {
appetizer.splice(index, i); // Pop that item if it's not exist
}
}
$scope.appetizers = appetizer; // Re-assign
}
Introduced variable flag that'll tell whether that array contains myAccess value or not. Based on that, I removed that index from that array variable appetizer. Finally, this array variable will replace scope variable.
I haven't checked the code. So, Just try or implement from yours using this logic if it suits.
EDIT - My code looks not much effective while comparing #HMR answer :)
Push appetizers into your array like this.
function myFunction() {
var myAccess = ["tomato"];
$scope.test = [];
var appetizer = $scope.appetizers;
for (var i = 0; i < appetizer.length; i++) {
for (var j = 0; j < appetizer[i].ingredient.length; j++) {
if (appetizer[i].ingredient[j].name === myAccess) {
// what should i write here
$scope.appetizers.push(appetizer[i]); // additional code here.
}
}
}
return null; }

How to add new key-value pair under Javascript object?

[{"name":"Top Level","parent":"null"}]
Required output:
[{
"name": "Top Level",
"parent": "null",
"children": [
{
"New_Key":"New_value"
}
]
}]
How can I add "New_Key":"New_value" pair under "parent" key?
var arr = [{"name":"Top Level","parent":"null"}];
for(var i=0; i<arr.length; i++){
arr[i].children = [{
"New_Key":"New_value"
}];
}
its very simple, you can add any new item like obj["key"] = value, in your case you can do it like below
var arrObj = [{"name":"Top Level","parent":"null"}];
for(var i=0; i<arrObj.length; i++){
arrObj[i].children = [{"New_Key":"New_value"}]

JavaScript compare two arrays(key/value pairs) and copy value from one to the other if key matches

I have two arrays containing key/value pairs.
{
"containerOne": [{
"Id": 1,
"Title": "TitleOne",
"Responsibility": "ValueOne"
}, {
"Id": 2,
"Title": "TitleTwo",
"Responsibility": "ValueTwo"
}]
}
{
"containerTwo": [{
"Id": 1,
"Title": "TitleOne",
"Responsibility": null
}, {
"Id": 2,
"Title": "TitleTwo",
"Responsibility": "null
}
]
}
I'd like to compare both arrays and compare the title of each container. If the titles match, then I'd like to copy the Responsibility value from containerOne to containerTwo. The ID's will not match, so that can be ruled out. Only the titles will be consistent.
What is the most efficient way to do this please?]
Thanks
=====================================================================
EDIT
=====================================================================
Looking at the arrays a little closer, there is a subtle difference in the data being returned:
{
"AMLookupTasksList":
[
{
"Id":1,
"Title":"Create and Maintain an Onboarding Document",
"Responsibility":"1. Onboarding|f101ccf1-c7d5-42e7-ba8f-48e88ac90a3d"
},
{
"Id":2,
"Title":"Execute Onboarding for New Consultants",
"Responsibility":"1. Onboarding|f101ccf1-c7d5-42e7-ba8f-48e88ac90a3d"
}
]
}
{
"AMTasksList":
[
{
"Id":4,
"Title":
{
"$M_1":13,"$c_1":"Create and Maintain an Onboarding Document"
},
"Responsibility":null
},
{
"Id":17,
"Title":
{
"$M_1":12,"$c_1":"Execute Onboarding for New Consultants"
},
"Responsibility":null
}
]
}
Do I have additional looping to get to the Title value in the second array?
This might be a bit of overkill but it ignores the sequence and does a look up in each object.
I had to fix some syntax in your objects but I include that: named the objects and took a quote off one of the null values.
var obj1 = {
"containerOne": [{
"Id": 1,
"Title": "TitleOne",
"Responsibility": "ValueOne"
}, {
"Id": 2,
"Title": "TitleTwo",
"Responsibility": "ValueTwo"
}]
};
var obj2 = {
"containerTwo": [{
"Id": 1,
"Title": "TitleOne",
"Responsibility": null
}, {
"Id": 2,
"Title": "TitleTwo",
"Responsibility": null
}]
};
Now the code:
// lookup for first object:
var lookup = {};
// create referece to list above and use it everywhere
lookup.list = obj1;
for (var i = 0, len = lookup.list.containerOne.length; i < len; i++) {
lookup[lookup.list.containerOne[i].Title] = lookup.list.containerOne[i];
}
// lookup for second object
var otherLookup = {};
otherLookup.list = obj2;
for (var i = 0, len = otherLookup.list.containerTwo.length; i < len; i++) {
otherLookup[otherLookup.list.containerTwo[i].Title] = otherLookup.list.containerTwo[i];
}
// copy value for Responsibility from first to second on each matched in second.
var i = 0;
var len = lookup.list.containerOne.length;
for (i; i < len; i++) {
// looks up value from second list in the first one and if found, copies
if (lookup[otherLookup.list.containerTwo[i].Title]) {
otherLookup.list.containerTwo[i].Responsibility = lookup[otherLookup.list.containerTwo[i].Title].Responsibility;
}
}
// alerts new value using lookup
alert(otherLookup["TitleOne"].Responsibility);
EDIT for new structure, but same answer really:
var obj1 = {
"AMLookupTasksList": [{
"Id": 1,
"Title": "Create and Maintain an Onboarding Document",
"Responsibility": "1. Onboarding|f101ccf1-c7d5-42e7-ba8f-48e88ac90a3d"
}, {
"Id": 2,
"Title": "Execute Onboarding for New Consultants",
"Responsibility": "1. Onboarding|f101ccf1-c7d5-42e7-ba8f-48e88ac90a3d"
}]
};
var obj2 = {
"AMTasksList": [{
"Id": 4,
"Title": {
"$M_1": 13,
"$c_1": "Create and Maintain an Onboarding Document"
},
"Responsibility": null
}, {
"Id": 17,
"Title": {
"$M_1": 12,
"$c_1": "Execute Onboarding for New Consultants"
},
"Responsibility": null
}]
};
var lookup = {};
// create refernece to list above and use it everywhere
lookup.list = obj1;
for (var i = 0, len = lookup.list.AMLookupTasksList.length; i < len; i++) {
lookup[lookup.list.AMLookupTasksList[i].Title] = lookup.list.AMLookupTasksList[i];
}
var otherLookup = {};
otherLookup.list = obj2;
for (var i = 0, len = otherLookup.list.AMTasksList.length; i < len; i++) {
otherLookup[otherLookup.list.AMTasksList[i].Title.$c_1] = otherLookup.list.AMTasksList[i];
}
// copy value for Responsibility from first to second
var i = 0;
var len = otherLookup.list.AMTasksList.length;
for (i; i < len; i++) {
if (lookup[otherLookup.list.AMTasksList[i].Title.$c_1]) {
otherLookup.list.AMTasksList[i].Responsibility = lookup[otherLookup.list.AMTasksList[i].Title.$c_1].Responsibility;
}
}
alert(otherLookup["Create and Maintain an Onboarding Document"].Responsibility);
Fiddle for second answer: http://jsfiddle.net/n22V8/
First, create a dictionary from containerTwo:
var c2dict = {};
var c2i = containerTwo.innerContainer;
for (var i = 0; i < c2i.length; i++) {
c2dict[c2i[i].Title] = c2i[i];
}
Now use this to do the copying of propertyies when titles match:
var c1i = containerOne.innerContainer;
for (var i = 0; i < c1i.length; i++) {
if (c2dict[c1i[i].Title]) {
c2dict[c1i[i].Title].Property = c1i[i].Property;
}
}
You should compare properties and set them as the following:
containerOne.innerContainer.forEach(function (element,index) {
containerTwo.innerContainer.forEach(function (element2,index2) {
if (element.Title === element2.Title && element.Property != element2.Property) {
element2.Property = element.Property;
}
});
});

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