I have an array of objects, say the object looks like following:
var row = {
data: 'test',
text: 'test'
};
I want to loop through the array and just get the object with text property.
What is the best way to do it?
So, I want to loop and the object should look like: row = {text: 'test'}
I tried something like below without luck:
arr.forEach(function (item){ //arr is the array of object
return {text: item.text};
});
Use Array.prototype.map for that:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
return {text: item.data};
});
The result will look like:
[{ text: 'testData' }]
If you want it to be [ {testText: 'testData' }] then:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
var obj = {};
obj[item.text] = item.data;
return obj;
});
As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.
var array = [
{
text : "text",
data : "data"
},
{
text : "text1",
data : "data1"
}
]
var newArray = array.map(function(item){
return item.data;
});
your output will look like
['text','text1']
Related
I'm using JSEL (https://github.com/dragonworx/jsel) for search data in a huge JSON. This is an extract:
{
"Clothes":[{
"id":"clothes",
"items":[{
"shoes":[{
"sizes":{
"S":{
"cod":"S1"
},
"M":{
"cod":"M1"
},
"L":{
"cod":"L1"
}
}
}],
"pants":[{
"sizes":{
"S":{
"cod":"PS1"
},
"M":{
"cod":"PM1"
},
"L":{
"cod":"L1"
}
}
}]
}]
}]
}
If I execute this command:
var dom = jsel(data);
console.log( dom.selectAll('//#cod') );
I obtain an array with all "cod" key values from JSON:
['S1', 'M1', 'L1', 'PS1', 'PM1', 'L1']
I'm newbie on XPath expressions and I want to get the parent keys of a certain "cod" key value, for example, if "cod" key value is "S1" the result is:
"shoes"
or
"items"
or
"Clothes"
How can I get it? I'd like to receive your help
There are lot of ways available in JS. I usually prefer this kind it's more quick and reusable in any kind of objects.
You can try below snippet and you will get it more clear.
var jsonString = '{"Clothes":[{"id":"clothes", "items":[{"shoes":[{"sizes":{"S":{"cod":"S1"}, "M":{"cod":"M1"}, "L":{"cod":"L1"} } }], "pants":[{"sizes":{"S":{"cod":"PS1"}, "M":{"cod":"PM1"}, "L":{"cod":"L1"} } }] }] }] }';
const myObj = JSON.parse(jsonString);
for (let i in myObj.Clothes) {
var clothes = myObj.Clothes[i];
var clothesId = clothes.id;
var clothesItems = clothes.items;
console.log(clothesId);
var products = Object.keys(clothesItems[0])
for( var productName in products ){
var productName = products[productName];
var productSizes = clothesItems[0][productName][0].sizes;
console.log(productName);
console.log(productSizes);
}
}
I have the following issue: In my app, I receive from the backend an string containing an comma separated list of numbers, which i convert to an array using join(). Then i get from another method an array containing several objects, like in this example:
strArray = [1,3]
objArray = [{'id':1,'name':'A'},
{'id':2,'name':'B'},
{'id':3,'name':'C'}]
I need to create another array based on this two array, expecting the following result:
resultArray = [{'id':1,'name':'A','selected': true},
{'id':2,'name':'B','selected': false},
{'id':3,'name':'C','selected': true}]
I've tried using map and function but without success. I'm quite new in javascript.
Would this help?
objArray.map(obj => {
obj['selected'] = strArray.indexOf(obj.id) != -1;
return obj;
});
try this:
strArray = [1, 3]
objArray = [{
'id': 1,
'name': 'A'
}, {
'id': 2,
'name': 'B'
}, {
'id': 3,
'name': 'C'
}]
var res = objArray.map(x => Object.assign(x, {
sel: strArray.includes(x.id)
}))
console.log(res)
but consider browser support for the proposed methods.
Hope this helps. By using simple .map
var strArray = [1,3];
var objArray = [{'id':1,'name':'A'},
{'id':2,'name':'B'},
{'id':3,'name':'C'}];
var resultArray = objArray.map(function(obj){
obj.selected = strArray.indexOf(obj.id) > -1;
return obj;
});
console.log(resultArray);
With map:
objArray.map(function(item){
return {id: item.id, name: item.name,selected: strArray.indexOf(item.id) > -1};
})
So I thought of using map(),but I'm stuck. I want to return arr2 but want to prompt the user whether there's changes or not by comparing it with arr. with below's approach, I got id of undefined if arr2 have any missing item.
https://jsfiddle.net/b13rbjyv/
var arr = [{
id: 1,
name: 'something'
}, {
id: 2,
name: 'something2'
}]
var arr2 = [{
id: 1,
name: 'something'
}, {
id: 2,
name: 'something2'
}]
var result = arr.map(function(obj, i) {
if (obj.id == arr2[i].id) {
return obj;
}
})
document.write(JSON.stringify(result))
you need to use filter
var result = arr.filter(function(obj, i) {
return obj.id == arr2[i].id;
})
map should be used if you want to change object for instance if you need to have array of id only then you should use it. For example if you want to get list of ids then
var result = arr
.filter(function(obj, i) { return obj.id == arr2[i].id; })
.map(function(obj){return obj.id;});
map returns an element for every given element of an array. It looks like what you need is actually to use filter. Perhaps something like this:
var result = arr.filter((elem, index) => elem.id === arr2[index].id);
This should be easy but for some reason I'm stuck -
if I have a json like this and need to convert it:
{ data : [
{id : data1, name : "Description"},
{id : data2, name : "Contribution"},
{id : data3, name : "Footer"},
]}
into something like this?
{
data : [
{ data1: "Description" , data2: "Contribution", data3: "Footer" },
]}
Thanks,
Stuart
A small Array.prototype.reduce should do the job:
var obj = {
data: [
{ id: 'data1', name: 'Description' },
{ id: 'data2', name: 'Contribution' },
{ id: 'data3', name: 'Footer' },
]
};
obj.data = obj.data.reduce(function (r, a) {
r[a.id] = a.name;
return r;
}, {});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
You can use a for loop over the array.
var newData = [];
for(var i=0;i<data['data'].length;i++){
var obj={};
obj[data['data'][i]['id']]=data['data'][i]['name'];
newData.push(obj);
}
console.log(newData);
Refer fiddle
Updated Answer
var newArray = data['data'].map(function(obj){
var rObj = {};
rObj[obj.id] = obj.name;
return rObj;
});
You can use Array.map method for that also.
Refer fiddle-map
You can try to use the underscore.js lib.
Then check this example for your desired result Group By
Enjoy ;-)
var array=[];
for(int i=0; i<data.length; i++){
var object={};
object[data[i].id=data[i].name];
array.push(obj);
}
You can do it almost in a single line using lodash:
var obj1 = { data : [
{id: "data1", name: "Description"},
{id: "data2", name: "Contribution"},
{id: "data3", name: "Footer"},
]};
var obj2 = {
data: _.zipObject(_.pluck(obj1.data, "id"),
_.pluck(obj1.data, "name"))
}
document.write(JSON.stringify(obj2, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Have a look at _.pluck and _.zipObject.
You can also use underscore but lodash is faster, more complete, and you can create custom build with only what you need.
I have an array:
var countries = ['Austria', 'America', 'Australia'];
I know you can turn that into an object with Underscore.js like this:
_.object(['name', 'name2', 'name3'], countries));
How can I turn the array into an array of objects that looks like this?
var countriesObject = [
{ name: 'Austria' },
{ name: 'America' },
{ name: 'Australia' }
];
(with all the keys named name).
No need to use Underscore.js for that. You can do it with plain javascript:
var new_arr = [];
countries.forEach(function(country) {
var new_obj = {};
new_obj.name = country;
new_arr.push(new_obj);
});
console.table(new_arr);
var countriesObject = _.map (countries,function (country){
return {
name: country
}
}