Use Object.keys() -
let data = [{"facebook":"https://facebook.com"}, {"instagram":"https://instagram.com"}]
data.forEach(social => console.log(Object.keys(social)[0]));
Here, I'm using .forEach() instead of .map() just to log the key's name, but the idea is the same with .map().
javascript - How do I get the key in array of objects using .map()? - Stack Overflow
javascript - Mapping Array Of Objects By Key - Stack Overflow
javascript - How to map an array of objects to an array of values by key - Stack Overflow
javascript - 'map' function for objects (instead of arrays) - Stack Overflow
Use Object.keys() -
let data = [{"facebook":"https://facebook.com"}, {"instagram":"https://instagram.com"}]
data.forEach(social => console.log(Object.keys(social)[0]));
Here, I'm using .forEach() instead of .map() just to log the key's name, but the idea is the same with .map().
If socials is your initial data array, then I would do following:
socials.map((social, index) =>
(
<View key={index}>
<Icon name={Object.keys(social)[0]} onPress={() => {}} />
</View>
)
)
var json = [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}];
var arr = [];
for(i=0;i<json.length;i++) {
arr.push(json[i].message);
}
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can use Array.map() or loop over the array and push the message to the array.
var a = [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}];
var b = a.map(function(obj){
return obj.message;
});
console.log(b);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
There is no native map to the Object object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
But you could easily iterate over an object using for ... in:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
Update
A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }
Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.
Update
With new ES6 features, there is a more elegant way to express objectMap.
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v))
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries() and Object.fromEntries():
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries, but you could use Object.keys instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries and Object.assign you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)
You could take the first key of the objects.
myArr1.map((key, value) => Object.keys(key)[0]);
function getData() {
const result = Object
.keys(myJSON.countries)
.map(k => myJSON.countries[k])
.map(({ currencies }) => currencies)
.map(currency => Object.keys(currency)[0]);
console.log(result);
}
var myJSON = { countryCode: { Australia: "AU", "United States": "US", Britain: "GB", Japan: "JP", India: "IND", France: "FR", Russia: "RS" }, countries: { AE: { currencies: { AED: { isDefault: true } } }, AL: { currencies: { ALL: { isDefault: true } } }, AU: { currencies: { AUD: { isDefault: true } } }, US: { currencies: { USD: { isDefault: true } } }, GB: { currencies: { EUR: { isDefault: true } } }, FR: { currencies: { EUR: { isDefault: true } } }, JP: { currencies: { JPY: { isDefault: true } } }, RS: { currencies: { RSD: { isDefault: false } } }, ZA: { currencies: { ZAR: { isDefault: true } } } } };
<button onclick="getData()">Get Data</button>
Or just in a single step:
function getData() {
const result = Object
.keys(myJSON.countries)
.map(k => Object.keys(myJSON.countries[k].currencies)[0]);
console.log(result);
}
var myJSON = { countryCode: { Australia: "AU", "United States": "US", Britain: "GB", Japan: "JP", India: "IND", France: "FR", Russia: "RS" }, countries: { AE: { currencies: { AED: { isDefault: true } } }, AL: { currencies: { ALL: { isDefault: true } } }, AU: { currencies: { AUD: { isDefault: true } } }, US: { currencies: { USD: { isDefault: true } } }, GB: { currencies: { EUR: { isDefault: true } } }, FR: { currencies: { EUR: { isDefault: true } } }, JP: { currencies: { JPY: { isDefault: true } } }, RS: { currencies: { RSD: { isDefault: false } } }, ZA: { currencies: { ZAR: { isDefault: true } } } } };
<button onclick="getData()">Get Data</button>
You can use map & for..in loop to iterate over the object
var myJSON = {
"countryCode": {
"Australia": "AU",
"United States": "US",
"Britain": "GB",
"Japan": "JP",
"India": "IND",
"France": "FR",
"Russia": "RS"
},
"countries": {
"AE": {
"currencies": {
"AED": {
"isDefault": true
}
}
},
"AL": {
"currencies": {
"ALL": {
"isDefault": true
}
}
},
"AU": {
"currencies": {
"AUD": {
"isDefault": true
}
}
},
"US": {
"currencies": {
"USD": {
"isDefault": true
}
}
},
"GB": {
"currencies": {
"EUR": {
"isDefault": true
}
}
},
"FR": {
"currencies": {
"EUR": {
"isDefault": true
}
}
},
"JP": {
"currencies": {
"JPY": {
"isDefault": true
}
}
},
"RS": {
"currencies": {
"RSD": {
"isDefault": false
}
}
},
"ZA": {
"currencies": {
"ZAR": {
"isDefault": true
}
}
}
}
};
function getData() {
// get countries object
let getCountries = myJSON.countries;
// get all country short names in an array
var ctr = Object.keys(getCountries);
// iterate that array using map
var getCur = ctr.map(function(item) {
// in countries object get the object where the country shortname
// matches the object key. Get the curriencies usin for ..in loop
for (let keys in getCountries[item].currencies) {
return keys
}
})
console.log(getCur)
}
<button onclick="getData()">Get Data</button>
Using Object#keys and Array#forEach:
const
myObj = {
prop1: 'prop1_value',
prop2: 'prop2_value',
subObj: { subProp1: 'subProp1_value', subProp2: 'subProp2_value', subProp3: 'subProp3_value', subprop4: 'subProp4_value' }
},
myArr = [ 'arrayVal_1', 'arrayVal_2', 'arrayVal_3', 'arrayVal_4' ];
const { subObj } = myObj;
Object.keys(subObj).forEach((prop, index) => { subObj[prop] = myArr[index] });
console.log(myObj);
You could do it with Object.fromEntries and Object.keys this way:
myObj.subObj = Object.fromEntries(Object.keys(myObj.subObj).map((k,i) => [k, myArr[i]]))
Be aware there are currently no safe-guards of any kind, so you might want to check if the two datastructures fit, before doing this.
If you have something that you can order by object's keys by, you can also use sort to ensure you assign the correct values to the correct keys, because the resulting order of Object.keys is not guaranteed
myObj.subObj = Object.fromEntries(Object.keys(myObj.subObj)
.sort((a,b) => a.localeCompare(b)) //sort keys ascending by name
.map((k,i) => [k, myArr[i]]))