Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Create an object with the property areas :
Take the array from the "mh" property of the source data. This is a JSON entry, so we just write
peremennaya = {...тут весь этот JSON...}
peremennaya.mh // тут нужный массив
var d = {"mh": [{"id": "BR", "count": 18516, "title": "Brazil"},
{"id": "US", "count": 4514, "title": "United States"},
{"id": "MY", "count": 390, "title": "Malaysia"},
{"id": "IT", "count": 208, "title": "Italy"}]
};
var result = {areas: d.mh.map(el => ({id:el.id, title:''+el.title+' - '+el.count}))}
// {"areas":[{"id":"BR","title":"Brazil - 18516"},{"id":"US","title":"United States - 4514"},
// {"id":"MY","title":"Malaysia - 390"},{"id":"IT","title":"Italy - 208"}]}
const some = { areas: mh.map((el) => ({ id: el.id, title: el.title })) }
The solution of this problem involves iterating over the elements of the array and creating transformed new values on its basis.
Theory of the question: Simple and Smart
Simple (canonical - pre-ES6) options: An
existing object to transform is given.
// Имеем объект, представляющий из себя массив простых объектов
oldObj = {"mh": [{"id": "BR", "count": 18516, "title": "Brazil"},
{"id": "US", "count": 4514, "title": "United States"},
{"id": "MY", "count": 390, "title": "Malaysia"},
{"id": "IT", "count": 208, "title": "Italy"}
]
};
// при желании функцию трансформации можно назвать конструктором со всеми вытекающими...
function transform(oO){
var rv = {}; // return value
rv.areas = oO.mh.map(function(str){
var rs = {}; // return string
rs.id = str.id;
rs.title = str.title + " - " + str.count;
return rs;
});
return rv;
};
var newObj1 = transform(oldObj);
// В случае конструктора
// var newObj1 = new Transform(oldObj)
console.log(newObj1);
// полученный объект
var newObj2 = {};
newObj2.areas = oldObj.mh.map(function(str){
var rs = {}; // return string
rs.id = str.id;
rs.title = str.title + " - " + str.count;
return rs;
});
var newObj3 = {"areas":[]};
oldObj.mh.forEach(function(str){
var ps = {}; // pushed string
ps.id = str.id;
ps.title = str.title + " - " + str.count;
newObj3.areas.push(ps);
});
var newObj4 = {"areas":[]};
for (var i = 0; i<oldObj.mh.length;i++) {
var str = oldObj.mh[i];
var ps = {};
ps.id = str.id;
ps.title = str.title + " - " + str.count;
newObj4.areas.push(ps);
}
Стрелочные функции, показанные в предыдущих ответах могут работать не во всех браузерах, хотя с точки зрения оптимизации кода - более эффективны...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question