Add new attribute to JSON? - javascript

I have JSON data and I want to update items on it.
How can I add a name attribute to ALL id's in controller ?
{
"games" : [
{ "id":["1"] },
{ "id":["2"] },
{ "id":["3"] },
{ "id":["4"] },
{ "id":["5"] },
{ "id":["6"] }
]
}
Should be :
{
"games" : [
{ "id":["1"],"name":"1" },
{ "id":["2"],"name":"2" },
{ "id":["3"],"name":"3" },
{ "id":["4"],"name":"4" },
{ "id":["5"],"name":"5" },
{ "id":["6"],"name":"6" }
]
}
for (var i = 1; i <= games.length; i++) {
games[].name = i;
}

Use forEach to loop through every items of the data.games array and then simply add the name property using game.name = game.id[0].
const data = {
"games" : [
{ "id":["1"] },
{ "id":["2"] },
{ "id":["3"] },
{ "id":["4"] },
{ "id":["5"] },
{ "id":["6"] }
]
};
data.games.forEach(game => game.name = game.id[0]);
console.log(data);

Related

try to filter the records from the array of objects

I have the array of objects and i am trying to show the records based upon some filtration,
I am doing in VUE
Here is my code
return this.system.filter(function (item, key) {
if(key.)
});
what i am tryin to achieve , if the key is: 1,2,3,4,5 it should be equal to 9 and display A because 9 is equal to A
because my keys are like this
this.system = [
{
key:0,"value:"x"
},
{
key:1,"value:"x1"
},
{
key:2,"value:"x2"
},
{
key:3,"value:"x3"
},
{
key:4,"value:"x4"
},
{
key:5,"value:"x5"
},
{
key:6,"value:"x6"
},
{
key:7,"value:"x7"
},
{
key:8,"value:"x8"
},
{
key:9,"value:"A"
},
{
key:10,"value:"B"
},
{
key:11,"value:"C"
},
{
key:12,"value:"D"
},
]
If I understood you correctly :
new Vue({
el: '#demo',
data() {
return {
system: [{key:0,value:"x"}, {key:1,value:"x1"}, {key:2,value:"x2" }, {key:3,value:"x3"}, {key:4,value:"x4"}, {key:5,value:"x5"}, {key:6,value:"x6"}, {key:7,value:"x7"}, {key:8,value:"x8"}, {key:9,value:"A"}, {key:10,value:"B"}, {key:11,value:"C"}, {key:12,value:"D"},],
chose: 0,
}
},
computed: {
result() {
return this.system.filter(item => {
if (+this.chose > 0 && +this.chose < 6 || +this.chose === 9) {
return item.key === 9
} else {
return item.key === +this.chose
}
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<input v-model="chose" type="number" />
{{ result }}
</div>
As per my understanding, You want to return value of value property based on the value of key property. If Yes, You can simply achieve that by using Array.find() method. Here you go :
const system = [
{
key:0,value:"x"
},
{
key:1,value:"x1"
},
{
key:2,value:"x2"
},
{
key:3,value:"x3"
},
{
key:4,value:"x4"
},
{
key:5,value:"x5"
},
{
key:6,value:"x6"
},
{
key:7,value:"x7"
},
{
key:8,value:"x8"
},
{
key:9,value:"A"
},
{
key:10,value:"B"
},
{
key:11,value:"C"
},
{
key:12,value:"D"
}
];
const res = system.find(({key}) => key === 9);
console.log(res.value);

Filter an array of object based on key name of the object

I have an array of objects that looks like this:
var data = [
{
abc: { name:"abc" }
},
{
new_abc: {name:"hello" }
},
{
def: { name:"def" }
},
{
ghi: { name:"ghi" }
},
{
new_ghi: { name:"world" }
},
{
new_jkl: { name:"javascript" }
},
{
lmn: { name:"lmn" }
},
];
I want only the objects that have a key whose name starts with "new". In the above array, I have 3 such objects.
I want the output to be this:
[
{
new_abc:{name:"hello"}
},
{
new_ghi:{name:"world"}
},
{
new_jkl:{name:"javascript"}
},
]
You can do the following,
var data = [
{
abc:{name:"abc"}
},
{
new_abc:{name:"hello"}
},
{
def:{name:"def"}
},
{
ghi:{name:"ghi"}
},
{
new_ghi:{name:"world"}
},
{
new_jkl:{name:"javascript"}
},
{
lmn:{name:"lmn"}
}
]
res = data.filter(item => Object.keys(item).some(key => key.indexOf('new') === 0));
console.log(res);
I want only the objects that have a key whose name starts with "new"
You can use Array#filter combined with String.prototype.startsWith() like this way.
const data = [{abc:{name:"abc"}},{new_abc:{name:"hello"}},{def:{name:"def"}},{ghi:{name:"ghi"}},{new_ghi:{name:"world"}},{new_jkl:{name:"javascript"}},{lmn:{name:"lmn"}}];
console.log(data.filter(item => Object.keys(item)[0].startsWith('new')));
The startsWith() method determines whether a string begins with the
characters of a specified string, returning true or false as
appropriate.

convert a flat array that has a "path" property to a nested array

I have a flat array like this example :
[
{
'name':'itemA',
'path':'foo/bar'
},
{
'name':'itemB',
'path':'bar/foo'
},
{
'name':'itemC',
'path':'foo'
},
{
'name':'itemD',
'path':'bar'
},
{
'name':'itemE',
'path':'foo/bar/wizz'
},
{
'name':'itemF',
'path':'bar/foo'
},
]
I want to build a tree based on the "path" property, so I could get this output :
[
{
'name':'itemD',
'path':'bar',
'items':[
{
'name':'itemD',
'path':'bar/foo'
},
{
'name':'itemF',
'path':'bar/foo'
}
]
},
{
'name':'itemC',
'path':'foo',
'items':[
{
'name':'itemA',
'path':'foo/bar',
'items':
[
{
'name':'itemE',
'path':'foo/bar/wizz'
}
]
},
]
}
]
How could I achieve that ?
I found out some examples like this one, but they are based on a parent ID and not a "path" like mine.
Thanks a lot !
You could find the level or add a new object for the level of the splitted path.
const
data = [{ name: 'itemA', path: 'foo/bar' }, { name: 'itemB', path: 'bar/foo' }, { name: 'itemC', path: 'foo' }, { name: 'itemD', path: 'bar' }, { name: 'itemE', path: 'foo/bar/wizz' }, { name: 'itemF', path: 'bar/foo' }],
tree = data.reduce((items, { name, path }) => {
path.split('/').reduce((o, _, i, p) => {
let path = p.slice(0, i + 1).join('/'),
temp = (o.items ??= []).find(q => q.path === path);
if (!temp) o.items.push(temp = { name, path });
return temp;
}, { items });
return items;
}, []);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to traverse in a tree and filter matching nodes in javascript?

I have tried to filter nodes, but succeed to filter only root nodes.
My implementation is below.
How can I use a methodology to filter also sub-nodes?
function getMatchedValues(nodes)
{
var leafContainsText = false;
for (var i = 0; i < nodes.length; i++)
{
if (nodes[i].items && nodes[i].items.length > 0)
{
leafContainsText = getMatchedValues(nodes[i].items);
if (leafContainsText)
break;
}
else
{
if (nodes[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
{
leafContainsText = true;
break;
}
}
}
return leafContainsText;
}
$scope.temp_reports = [];
for (var i = 0; i < $scope.reports.length; i++)
{
if ($scope.reports[i].items && $scope.reports[i].items.length > 0)
{
if (getMatchedValues($scope.reports[i].items))
$scope.temp_reports.push($scope.reports[i]);
else if ($scope.reports[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
$scope.temp_reports.push($scope.reports[i]);
}
else
{
if ($scope.reports[i].text.toLowerCase().indexOf($scope.filterReports.toLowerCase()) !== -1)
$scope.temp_reports.push($scope.reports[i]);
}
}
The tree object($scope.reports) looks likes below:
[
{
text:"abc",
items:[
{
text:"abf"
},
{
text:"abd",
items:[
{
text:"bbb"
},
{
text:"dba"
}
]
}
]
},
{
text:"def",
items:[
{
text:"ddf"
},
{
text:"ddd",
items:[
{
text:"dfg"
},
{
text:"dba",
items:[
{
text:"qqq"
},
{
text:"www"
}
]
}
]
}
]
}
]
For example, If want to filter nodes that contain 'd' then result tree should look like this;
[
{
text:"abc",
items:[
{
text:"abd",
items:[
{
text:"dba"
}
]
}
]
},
{
text:"def",
items:[
{
text:"ddf"
},
{
text:"ddd",
items:[
{
text:"dfg"
},
{
text:"dba",
items:[]
}
]
}
]
}
]
You could filter the array by filtering the items array as well.
This solution mutates the original data.
function filter(array, search) {
return array.filter(function f(o) {
var t;
if (o.items) {
t = o.items.filter(f);
}
if (o.text.includes(search) || t && t.length) {
if (t) {
o.items = t;
}
return true;
}
});
}
var array = [{ text: "abc", items: [{ text: "abf" }, { text: "abd", items: [{ text: "bbb" }, { text: "dba" }] }] }, { text: "def", items: [{ text: "ddf" }, { text: "ddd", items: [{ text: "dfg" }, { text: "dba", items: [{ text: "qqq" }, { text: "www" }] }] }] }],
result = filter(array, 'd');
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Underscore multidimensional sortBy

I have an object.
[
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
]
How can I sort this object with mesafe field order by ASC numeric using underscore ?
You can consider
{
"home1": {
"mesafe":11
}
}
as
{
"home1": {
"mesafe":11
},
// fakes
"home2": {},
"home3": {}...
}
Now the value to sort can be described to :
Get all mesafe attribute's value from subObject and sum them up (if the attribute exist).
So you can use _.reduce to achieve it.
var list = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
var sortedList = _.sortBy(list, function(item) {
// For each item, we acts as there not only have one attribute "homex", but there's many other like "homey : {}".
var res = _.reduce(item, function(res, sub) {
// So we can the again use reduce to iterate through them, and add the value if mesafe exist.
return (sub.mesafe == null) ? res : res + sub.mesafe;
}, 0);
return res;
});
console.log(sortedList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You can use JavaScript Array sort() Method to sort the array based on value in mesafe field.
var data = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
// get the value from mesafe field
function getMesafeValue(a) {
for (var key in a) {
if (a.hasOwnProperty(key)) {
return a[key].mesafe;
}
}
}
// sort the array
data.sort(function(a, b) {
var v1 = getMesafeValue(a);
var v2 = getMesafeValue(b);
return v1 < v2 ? -1 : (v1 > v2 ? 1 : 0);
});
// print the array after sorting
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (data[i].hasOwnProperty(key)) {
document.write(key + " -> " + data[i][key].mesafe + '<br/>');
}
}
}

Categories

Resources