In my react native app, i stored an object locally and retrieved it, worked fine but now i wanted to append an another object to previous object, like i have two objects:
const obj1 = {key1: keyone, key2: keytwo}
const obj2 = {key4: keyfour, key6: keysix}
All i want back is an object as
{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }
and im trying to do it as:
const newVal = `${obj1}, ${obj2}`
which returns "object Object"
I went through Object.assign() and also through lodash's .merge() functionality but it seems to be they are merging common fields in object.
How do i acheive this?
1. If you want to have an array of objects then you can use this approach:
const arr = [obj1, obj2];
it will provide you with the following result:
[{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }]
2. If you want to have the object of objects then you can try this:
const arr = {obj1, obj2};
this lead to following result:
{ obj1: { key1: keyone, key2: keytwo }, obj2: { key4: keyfour, key6: keysix }}
3. If you want a single object you can try this:
const arr = {...obj1, ...obj2};
will produce the following result:
{ key1: keyone, key2: keytwo, key4: keyfour, key6: keysix }
You can use spread operator (...)
const obj1 = {key1: 1, key2: 2};
const obj2 = {key4: 4, key6: 6};
const newVal = {...obj1, ...obj2 };
console.log(newVal);
You have an object A = {"a": 1, "b": 2} and an object B = {"c": 3, "d": 4}. You want an object C that contains both as individual objects (hence the syntax in your question):
var C = {A, B}; //{{"a": 1, "b": 2}, {"c": 3, "d": 4}}
Your desired output is an Object itself containing two objects without keys, my suggestion would be to output an Array of objects which somewhat results to your output.
[obj1, obj2] = [{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }]
Related
So lets say I have an object like this:
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
And I want an array of the keys, but only if the have a value. i.e. if they're undefined or empty string, I don't want them included in the array.
Currently I'm using Object.keys(myObject) but this gets all the keys including those that are undefined, false or nullable value.
I completely understand I can likely write my own version of the keys method from Object, but I'm wondering if there's an easier way than that.
Filter the entries by whether the key portion of the entry is truthy, then map to the keys:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.entries(myObject)
.filter(([, val]) => val)
.map(([key]) => key);
console.log(keys);
You only need to use Array.filter() to remove the keys that have nullable results
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject)
.filter(key => myObject[key])
console.log(keys);
If all you care about are the truthy keys you can use a somewhat simpler filter than above:
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
truthyKeys = Object
.keys(myObject) // array of all keys
.filter(k => myObject[k]) // filter out ones with falsy values
console.log(truthyKeys)
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject).filter(key => myObject[key]);
This will also cut out other falsy values however, such as 0, NaN, null, false. If you very specifically are guarding against empty strings and undefined:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject)
.filter(key => myObject[key] !== '' && myObject[key] !== undefined);
I don't know if there is another way but you can try something like this
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
const getValue = (obj) => {
const array = [];
for (const [key, value] of Object.entries(obj)) {
if(value){
array.push(key);
}
}
return array;
}
console.log(getValue(myObject));
let objectWithTruthyKeys = Object.keys(myObject).filter(i => myObject[i]);
Explanation:
Object.keys will get all the keys of the property (including the ones that contain falsy values).
The filter will go through each key in myObject (represented by i). the condition will be true only if the value is truthy, hence, filtering out the keys which contain falsy values.
There's a couple ways to do that. You could use filter:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
var keysWithValues = Object.keys(myObject).filter(key => myObject[key]);
console.log(keysWithValues);
Or a for loop:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
var keysWithValues = [];
for (const [key, value] of Object.entries(myObject)) {
if (value) {
keysWithValues.push(key);
}
}
console.log(keysWithValues);
You could also be fancy and extend Object by creating a class. But I believe that would be overkill :D
try it.
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
let x= Object.entries(myObject);
for(i=0;i<x.length;i++){
if(x[i][1]!==undefined&&x[i][1]!==""){
console.log(x[i][0])}
}
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I have an array of objects, similar to the below:
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
and I would like to get an array containing all the values stored in, say, key2.
At the moment, my code looks as follows:
const valueArray = [];
objectArray.forEach((object) => {
valueArray.push(object.key2);
});
This then results in
const valueArray = ['value2a', 'value2b', 'value2c'];
It feels like there is probably a more eloquent way to achieve the same thing, in just one line but I can't for the life of me figure out how to do that - can someone point me towards some documentation, or example code on how to do that please
Array.prototype.map()
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},
{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},
{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
const result = objectArray.map(obj => obj.key2);
console.log(result);
You can map objectArray:
const valueArray = objectArray.map(o => o.key2);
You can use Array#map (which creates a new array with the result of applying a callback with each element) with destructuring.
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
const res = objectArray.map(({key2})=>key2);
console.log(res);
Here is how you can do it for any key:
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
}, {
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
}, {
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
function getByKey(key) {
return objectArray.reduce((acc, red) => acc = [...acc, red[key]], [])
}
console.log(getByKey("key2"));
How can I turn the array:
data = [
{key1: a, key2: 1},
{key1: b, key2: 2},
{key1: c, key2: 3}]
into the array:
newArray = [1, 2, 3]
using reduce?
You do not want to reduce (transform an array into a single element) but you try to map (transform an array into another array)
data = [
{key1: 'a', key2: 1},
{key1: 'b', key2: 2},
{key1: 'c', key2: 3}
]
console.log(data.map(el => el.key2))
I don't know what are you really want, but seeing your example if you want to create a new array with the values of particular key in the object with reduce you can do it something like this:
const data = [
{key1: "a", key2: 1},
{key1: "b", key2: 2},
{key1: "c", key2: 3}
];
const ans = data.reduce((prev, curr) => {
prev.push(curr.key2);
return prev;
}, []); // start with empty array
// ans: [ 1, 2, 3 ]
But, if you want to separate all the keys in a new set of arrays you can do it something like this:
const data = [
{key1: "a", key2: 1},
{key1: "b", key2: 2},
{key1: "c", key2: 3}
];
const ans = data.reduce((prev, curr) => {
Object.keys(curr).forEach((key) => {
if (!prev[key]) {
prev[key] = [curr[key]];
} else {
prev[key].push(curr[key]);
}
});
return prev;
}, {}); // start with empty object
// ans: { key1: [ 'a', 'b', 'c' ], key2: [ 1, 2, 3 ] }
As my recommendation, I prefer using for..of is cleaner and faster than reduce or forEach or map
Example of both:
// Example 1:
const ans = [];
for (const obj of data) {
ans.push(obj.key2);
}
// ans: [ 1, 2, 3 ]
// Example 2:
const ans = {};
for (const obj of data) {
for (const key of Object.keys(obj)) {
if (!ans[key]) {
ans[key] = [obj[key]];
} else {
ans[key].push(obj[key]);
}
}
}
// ans: { key1: [ 'a', 'b', 'c' ], key2: [ 1, 2, 3 ] }
I receive an object and each time it different quantity of strings different every time
Object {
key_id: 7,
key1: "String1, String2",
key2: "String1, String2, String3",
key3: "String1, String2",
key4: "String1, String2";
…
}
I want to receive
Array = [{key_id: 7, key1: "String1", key1: "String2" ...}]
or
Array = [{key_id: 7, key1: "String1", "String2" ...}]
I need that to make this strings separated to make from them separated links.
I am making it on ReactJs with JSX/Babel ES6
Use Object#entries to convert to an array of [key, value] pairs, and Array#map them:
const data = {
key_id: 7,
key1: "String1, String2",
key2: "String1, String2, String3",
key3: "String1, String2",
key4: "String1, String2"
};
const result = Object.entries(data).map(([key, value]) => ({
[key]: typeof value === 'string' ? value.split(', ') : value
}));
// an array with multiple objects
console.log(result);
// A single object:
console.log(Object.assign({}, ...result));
Note that Object#entries is not part of ES6, and is not supported by IE and Edge.
EDIT: Updated the code to change each property to array element.
let data = {
key_id: 7,
key1: "String1, String2",
key2: "String1, String2, String3",
key3: "String1, String2",
key4: "String1, String2"
};
Object.keys(data).forEach(function(key) {
data[key] = typeof data[key] === 'string' ? data[key].split(', ') : data[key];
});
console.log(data);
I have an array of objects and I want to get a new array with objects that will have only some of the initial values.
var obj = [{
key1: 'someValue',
key2: 'someValue',
key3: 'someValue'
}, {
key1: 'someValue2',
key2: 'someValue2',
key3: 'someValue2'
}]
I am looking something like Underscore's _.pluck but for more than one values that will give me as a result.
[{
key1: 'someValue',
key2: 'someValue'
}, {
key1: 'someValue2',
key2: 'someValue2'
}]
If there are multiple items in object and you want to only keep few, you can use pick.
_.map(arr, o => _.pick(o, ['key1', 'key2']))
Demo
You can use map with omit.
_.map(arr, o => _.omit(o, 'key3'))
Demo
This is fairly easy with JavaScript's built-in map:
Using an ES2015 arrow function:
var newArray = initialArray.map(e => ({key1: e.key1, key2: e.key2}));
var initialArray = [
{key1: 'someValue', key2: 'someValue', key3: 'someValue'},
{key1: 'someValue2', key2: 'someValue2', key3: 'someValue2'}
];
var newArray = initialArray.map(e => ({key1: e.key1, key2: e.key2}));
document.body.innerHTML = "<pre>" + JSON.stringify(newArray, null, 2) + "</pre>";
Using an old-style function:
var newArray = initialArray.map(function(entry) {
return {key1: entry.key1, key2: entry.key2};
});
var initialArray = [
{key1: 'someValue', key2: 'someValue', key3: 'someValue'},
{key1: 'someValue2', key2: 'someValue2', key3: 'someValue2'}
];
var newArray = initialArray.map(function(entry) {
return {key1: entry.key1, key2: entry.key2};
});
document.body.innerHTML = "<pre>" + JSON.stringify(newArray, null, 2) + "</pre>";
map calls the callback once for each entry in an array, and builds a new array out of the values you return from the callback. So in the above, we're returning new objects with just key1 and key2.
(I renamed obj to initialArray because while arrays are objects, I wanted to emphasize that we were dealing with an array.)