Javascript push list on object empty array - javascript

I am trying to get a list of tags from an object
Here is the full code and data:
$(document).ready(function() {
obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]
};
var tagList = [];
for (var index in obj) {
for (var indexSub in obj[index].tags) {
blah = (obj[index].tags[indexSub]);
tagList.push(blah);
}
}
console.log(tagList);
});
Here's a link to jsFiddle
The problem is that taglist is returning an empty array.
How can I fix this?

Yours
for (var index in obj) {
for (var indexSub in obj[index].tags) {
blah = (obj[index].tags[indexSub]);
tagList.push(blah);
}
}
New to get the tags that are into the category
for (var index in obj) {
for (var indexSub in obj[index]) {
blah = (obj[index][indexSub].tags);
tagList.push(blah);
}
}
See the diference in the way to access the properties
obj =
{
"category": [
{
"id": "8098",
"tags": {
"411": "something",
"414": "something else"
}
}
]
};
var tagList = [];
for (var index in obj) {
for (var indexSub in obj[index]) {
tagList = (obj[index][indexSub].tags);
// tagList.push(blah);
}
}
console.log(tagList);

You need to iterate the category, and then get the keys and values of tags, somethig like this..
var obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]};
var tagList = [];
obj.category.forEach( o =>{
for (property in o.tags){
tagList.push(property + ':'+ o.tags[property]);
};
});
console.log(tagList);

Here is your jsfiddle
obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]
};
var tagList = [];
for (key in obj) {
for(subKey in obj[key]){
var myTags=obj[key][subKey].tags;
for(tag in myTags){
tagList.push(tag);
}
}
}
console.log(tagList);

You could use Array#reduce and Object.keys with Array#map for iterating and getting all tags.
var obj = { "category": [{ "id": "8098", "tags": { "411": "something", "414": "something else" } }] },
tagList = obj.category.reduce(function (r, a) {
return r.concat(Object.keys(a.tags).map(function (t) { return a.tags[t]; }));
}, []);
console.log(tagList);

Related

JavaScript: How to convert nested array of object to key-value pair objects

It can be duplicate question but i have tried a lot but i did not get expected result.Could some one help me.
I am getting an array in request body like :
[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
And I need to convert the array of nested array to below format
{
array: [
{
name1: "book1"
},
{
name2: "book2"
}
],
name3: "book3"
}
Note:In some cases book can be array or string.
On my first attempt i have tried below code to convert it into single object but it doest not convert nested array to key value pair
const array=[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
var result = {};
for (var i = 0; i < array.length; i++) {
result[array[i].name] = array[i].value;
}
console.log(result);
Response for the above code
{
array: [
{
name: "name1",
book: "book1"
},
{
name: "name2",
book: "book2"
}
],
name3: "book3"
}
EDITED
I have made little change in the Code from the Ahmed's answer and it worked
const res=[
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
const obj = {}
for(let i = 0 ; i < res.length; i++){
let name = res[i].name
if(Array.isArray(res[i]['book'])){
obj[name] = [];
for(let item in res[i]['book']){
let key = res[i]['book'][item]['name']
let value = res[i]['book'][item]['book']
let entry = {}
entry[key] = value
obj[name].push(entry)
}
}
else{
obj[res[i].name]=res[i].book;
}
}
console.log(obj);
The added snippet should solve your problem.
The problem in your code was Appropriate nesting you didn't access the wanted values and didn't handle all the cases Hence, The wrong output.
const res = [
{
"name":"array",
"book":[
{
"name":"name1",
"book":"book1"
},
{
"name":"name2",
"book":"book2"
}
]
},
{
"name":"name3",
"book":"book3"
}
]
const obj = {}
for(let i = 0 ; i < res.length; i++){
let name = res[i].name
if(Array.isArray(res[i]['book'])){
obj[name] = []
for(let item in res[i]['book']){
let key = res[i]['book'][item]['name']
let value = res[i]['book'][item]['book']
let entry = {}
entry[key] = value
obj[name].push(entry)
}
}
else{
obj[name] = res[i]['book']
}
}
for(let item in obj){
console.log(item)
console.log(obj[item])
}

How can I filter a JSON object in JavaScript?

I've got the following JSON string:
{
"Alarm":{
"Hello":48,
"World":3,
"Orange":1
},
"Rapid":{
"Total":746084,
"Fake":20970,
"Cancel":9985,
"Word": 2343
},
"Flow":{
"Support":746084,
"About":0,
"Learn":0
}
}
Then I load the above string and convert it to json object:
jsonStr = '{"Alarm":{"Hello":48,"World":3,"Orange":1},"Rapid":{"Total":746084,"Fake":20970,"Cancel":9985},"Flow":{"Support":746084,"About":0,"Learn":0}}';
var jsonObj = JSON.parse(jsonStr);
Now, how can I filter this json object by key name?
E.g., if the filter was "ange", the filtered object would be:
{
"Alarm":{
"Orange":1
}
}
If the filter was "flo", the filtered object would become:
{
"Flow":{
"Support":746084,
"About":0,
"Learn":0
}
}
And if the filter was "wor", the result would be:
{
"Alarm":{
"World": 3,
},
"Rapid":{
"Word": 2343
}
}
Is it possible to achieve this filtering using the filter method?
Beside the given solutions, you could use a recursive style to check the keys.
This proposal gives the opportunity to have more nested objects inside and get only the filtered parts.
function filterBy(val) {
function iter(o, r) {
return Object.keys(o).reduce(function (b, k) {
var temp = {};
if (k.toLowerCase().indexOf(val.toLowerCase()) !== -1) {
r[k] = o[k];
return true;
}
if (o[k] !== null && typeof o[k] === 'object' && iter(o[k], temp)) {
r[k] = temp;
return true;
}
return b;
}, false);
}
var result = {};
iter(obj, result);
return result;
}
var obj = { Alarm: { Hello: 48, "World": 3, Orange: 1 }, Rapid: { Total: 746084, Fake: 20970, Cancel: 9985, Word: 2343 }, Flow: { Support: 746084, About: 0, Learn: 0 }, test: { test1: { test2: { world: 42 } } } };
console.log(filterBy('ange'));
console.log(filterBy('flo'));
console.log(filterBy('wor'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can create a function using reduce() and Object.keys() that will check key names with indexOf() and return the desired result.
var obj = {
"Alarm": {
"Hello": 48,
"World": 3,
"Orange": 1
},
"Rapid": {
"Total": 746084,
"Fake": 20970,
"Cancel": 9985,
"Word": 2343
},
"Flow": {
"Support": 746084,
"About": 0,
"Learn": 0
}
}
function filterBy(val) {
var result = Object.keys(obj).reduce(function(r, e) {
if (e.toLowerCase().indexOf(val) != -1) {
r[e] = obj[e];
} else {
Object.keys(obj[e]).forEach(function(k) {
if (k.toLowerCase().indexOf(val) != -1) {
var object = {}
object[k] = obj[e][k];
r[e] = object;
}
})
}
return r;
}, {})
return result;
}
console.log(filterBy('ange'))
console.log(filterBy('flo'))
console.log(filterBy('wor'))
With the filter method I think you mean the Array#filter function. This doesn't work for objects.
Anyway, a solution for your input data could look like this:
function filterObjects(objects, filter) {
filter = filter.toLowerCase();
var filtered = {};
var keys = Object.keys(objects);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (objects.hasOwnProperty(key) === true) {
var object = objects[key];
var objectAsString = JSON.stringify(object).toLowerCase();
if (key.toLowerCase().indexOf(filter) > -1 || objectAsString.indexOf(filter) > -1) {
filtered[key] = object;
}
}
}
return filtered;
}

Construct new object in JS using [ ] notation

I'm trying to build a new object from an old object recursively like:
var arr = {};
var markCheckBoxes = function(obj){
var trackArr = new Array();
for(var prop in obj){
if(!!obj[i] && typeof(obj[i])=="object"){
trackArr.push(i);
markCheckBoxes(obj[i]);
trackArr.pop();
}
else{
var str = trackArr.join(".") + "." + i;
arr[str] = true;
}
}
};
But this creates a flat object. For example if obj is:
obj = {
prop1: {
subprop1: "text",
subprop2: "extra"
}, prop2:{
subprop: {another: 3}
}
}
Then the above function creates an object with keys:
{
"prop1.subprop1": true,
"prop1.subprop2": true,
"prop2.subprop.another": true
}
Assuming OP want to make other copy of object with true value for the keys, you can modify the code as below
var makeChecks = function(obj){
var cloneTo = {};
for(var prop in obj){
if(obj.hasOwnProperty(prop) && typeof(obj[prop]) === 'object'){
cloneTo[prop] = makeChecks(obj[prop]);
}
else{
cloneTo[prop] = true;
}
}
return cloneTo;
}
var obj = {
prop1: {
subprop1: "text",
subprop2: "extra"
}, prop2:{
subprop: {another: 3}
}
}
var output = makeChecks(obj);
console.log(output)
/*
{
"prop1": {
"subprop1": true,
"subprop2": true
},
"prop2": {
"subprop": {
"another": true
}
}
}
*/

Remove duplicate values from json array using angular js

I want to remove duplicates from the following json array
$scope.array = [
{"name":"aaa","key":"1"},
{"name":"bbb","key":"2"},
{"name":"aaa","key":"1"},
{"name":"ccc","key":"3"},
{"name":"bbb","key":"2"}
];
I tried following code but its not working
var ids = {};
$scope.array.forEach(function (list) {
ids[list.name] = (ids[list.name] || 0) + 1;
});
var finalResult = [];
$scope.array.forEach(function (list) {
if (ids[list.name] === 1) finalResult.push(student);
});
console.log(finalResult);
This is the expected result.
$scope.array = [
{"name":"aaa","key":"1"},
{"name":"bbb","key":"2"} ,
{"name":"ccc","key":"3"}
];
You can do something like this using Array#filter
$scope = {};
$scope.array = [{
"name": "aaa",
"key": "1"
}, {
"name": "bbb",
"key": "2"
}, {
"name": "aaa",
"key": "1"
}, {
"name": "ccc",
"key": "3"
}, {
"name": "bbb",
"key": "2"
}];
var ids = {};
$scope.array = $scope.array.filter(function(v) {
var ind = v.name + '_' + v.key;
if (!ids[ind]) {
ids[ind] = true;
return true;
}
return false;
});
console.log($scope.array);
You can use the unique filter.
<tr ng-repeat="arr in array | unique: 'key'" >
<td> {{ arr.name }} , {{ arr.key }} </td>
</tr>
You can use
$scope.array = = [{
"testada": "ecom",
"id": "27"
}, {
"testada": "alorta",
"id": "27"
}, {
"testada": "france24",
"id": "23"
}, {
"testada": "seloger",
"id": "23"
}];
var arr = [],
collection = [];
$scope.array.forEach(json_all, function (index, value) {
if ($.inArray(value.id, arr) == -1) {
arr.push(value.id);
collection.push(value);
}
});
console.log(json_all);
console.log(collection);
console.log(arr);
$scope.array = [
{"name":"aaa","key":"1"},
{"name":"bbb","key":"2"},
{"name":"aaa","key":"1"},
{"name":"ccc","key":"3"},
{"name":"bbb","key":"2"}
];
var newArr = []; //this will be new array with no duplicate value
for (var i = 0; i < $scope.array.length; i++) {
if(!ifContains($scope.array[i])){
newArr.push($scope.array[i]);
}
}
function ifContains(obj){
debugger
var flag = false;
for(var i = 0; i < newArr.length; i++){
if(newArr[i].name == obj.name && newArr[i].key == obj.key )
return true;
else
flag = false;
}
return flag;
}
It can be very simply done by pure JS. An invention of Object.prototype.compare() will help us enormously. Let's see how it works;
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
var myArray = [
{"name":"aaa","key":"1"},
{"name":"bbb","key":"2"},
{"name":"aaa","key":"1"},
{"name":"ccc","key":"3"},
{"name":"bbb","key":"2"}
],
filtered = myArray.reduce((p,c) => p.findIndex(f => c.compare(f)) == -1 ? p.concat(c) : p,[]);
console.log(JSON.stringify(filtered));
Note: Object.prototype.compare() v.01 won't do deep object comparison as of now.
var uniqueList = _.uniq($scope.array, function (item) {
return item.key;
});
console.log(uniqueList);
use underscore.js, anyone helps out so post later.
you can use pure javascript!
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
in your case:
var finalResult = [];
finalResult = $scope.array.filter(function(item, pos) {
return array.indexOf(item) == pos;
})

How find a object by ID in a JavaScript object which could have a variable structure?

I would like to know what is the faster way to retrieve an object by its id, keeping in consideration that the structure where it is stored could be different.
Does any native function in JS for this operation?
Example 1
var source = {
"page": [{
"id": "1",
"site": "",
"items": [{
"id": "2"
}, {
"id": "3",
"anotherItem": [{
"id": "4"
}, {
"id": "5"
}]
}]
}, {
"id": "6"
}]
};
Example 2
Structure could be completely different, the script should be always able to get the object containing id.
{
"smtElse": {
"id": "1"
}
}
No, there is no native function.
The fastest way is the same as the only way which is to iterate over the object, probably recursively, looking for IDs and returning what you want.
I solved using the following script, as it seems no native functionality is available.
var data = {
item: [
{
itemNested: [
{
itemNested2: [{
id: "2"
}
]
}
]
}
]
};
function findById(obj, id) {
var result;
for (var p in obj) {
if (obj.id == id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
var result = findById(data, "2");
console.log(result);
you can try this
<script type="text/javascript">
var re = /"id":\s+"(.*?)"/;
var sourcestring = "source string to match with pattern";
var results = [];
var i = 0;
for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {
results[i] = matches;
for (var j=0; j<matches.length; j++) {
alert("results["+i+"]["+j+"] = " + results[i][j]);
}
i++;
}

Categories

Resources