I have an object array with object key value.
arr = [obj1:{name:"Jack", surname:"Peralto"}, obj2:{name:"Husnu", surname:"White"}]
I do not want to see obj1 and obj2 labels. Because of these labels I could not use a word template package.
So I want to convert it to this form.
arr = [{name:"Jack", surname:"Peralto"}, {name:"Husnu", surname:"White"}]
.map function does not work at first array.
arr.map(o=>o)
Why I have an array like this? I should use reduce function and obj1 and obj2 labels are key value when I create object array. Now I don't need them.
When you fix the syntax errors in your code ([obj1:{... is not a valid data structure) you can use Object.values to get at the nested objects.
const obj = {
obj1: {
name: "Jack",
surname: "Peralto"
},
obj2: {
name: "Husnu",
surname: "White"
}
};
console.log(Object.values(obj));
its not the right syntax of array you have used array don't have key value pair
use this syntax if you are using object of objects with key value pair
const obj = {
obj1: {
name: "Jack",
surname: "Peralto"
},
obj2: {
name: "Husnu",
surname: "White"
}
};
or use this an array contains object
arr = [
{name:"Jack", surname:"Peralto"},
{name:"Husnu", surname:"White"}
]
Related
const obj1 = { name: "kim", age: 14 };
const obj2 = { name: "Steve", age: 20};
const arr = [ obj1, obj2];
arr[0]["name"].includes("han"); // true
so this is the code that I am curious.
I think includes() method is for array, not for object.
but in this case arr is array but arr[0] is object. also arr[0]["name"] is property of object, then why is it possible to use includes method on this code?
I would be grateful if someone tell me what I know wrong
You can use includes on Arrays or on strings.
According to you code includes doesn't give true because It doesn't work on an object. Instead, you are using it on a string.
When you console
arr[0]["name"] // kim
And what your code is checking is whether han is a substring of kim or not. As we know it's not so it will output false
const obj1 = { name: "kim", age: 14 };
const obj2 = { name: "Steve", age: 20 };
const arr = [obj1, obj2];
console.log(arr[0]["name"]);
console.log(arr[0]["name"].includes("m"));
includes() check if a sub string is present in the given string.
In your case :
arr[0]["name"].includes("han")
It should return false, as "kim" does not include "han".
I found unexpected result when try to merge with lodash object with flat array inside.
Here the example:
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
var people2 = { name: 'Andrew', age: '30', values: [{ pippo : 1}] };
const person2 = { age: '31', values: [{ pippo : 2}] };
// Now merge person back into people array
console.log(_.merge({}, people, person));
console.log(_.merge({}, people2, person2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
The result of first console.log is
{
age: "31",
name: "Andrew",
values: ["PT", "PORTA 31"]
}
And not as expected
{
age: "31",
name: "Andrew",
values: ["PT"]
}
Someone can explain me why and give me a solution to make sure that with a flat array it takes me the correct value
I think assign is better in this case than merge
This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
console.log(_.assign({}, people, person));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
I believe _.assign(people, person) would produce the desired outcome in this case https://lodash.com/docs/4.17.15#assign
This functionality is also native and can be used like this Object.assign(target, source)
I got a Javascript object which looks like this:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
}
}
I also got an array to which I push items like this:
myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
},
key3: { //the object that was added },
key4: { //the object that was added }
}
I tried doing it with the spread operator:
return {...object, ...myArr}
But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).
How do I concatenate the object and the array the way I want?
rather my myArray create myObject.
myObject = {}
myObject[item.itemId] = anotherDefinedObject;
Then
return {...object, ...myObject}
const obj = {key1: 1};
const myArr = [{key2: 2}];
myArr.forEach(val => Object.assign(obj, val));
console.log(obj); // {key1: 1, key2: 2}
What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code.
P.S. As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it.
Say I have an object:
myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2', three: '3'} // (Edited) Added one more key here :)
};
I want a copy of this object without certain keys to a new object in a way that the output is as below:
newObj = {
name: 'Luke',
age: 12,
one: '1',
two: '2'
};
I have seen examples of destructing but I wanted to know if it is possible with nested objects. Is something like this doable using destructuring or if not what would be the most efficient way to do this.
One way to achieve this with destructure-like syntax would be like this:
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2', three : '3'}
};
const newObj = {
/* Copy over values from "myObj" to equivalent keys in "newObj" */
name : myObj.name,
age : myObj.age,
/* Spread keys "one" and "two" of the nested "others" object into "newObj" */
...({one, two} = myObj.others, {one, two})
}
console.log(newObj)
For completeness, an iife approach is possible. It works by creating an arrow function that takes as parameters keys you want to keep. In the function body, spread nested objects as desired.
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2'}
};
const newObj = (
({name, age, others}) => ({name, age, ...others})
)(myObj);
console.log(newObj);
For the object of unknown depth you can try using recursion.
Create a function which takes an object and array of keys to be removed as arguments.
Create a helper(which takes 1 object as parameter) function inside main and create empty object.
Loop through the properties of obj using for..in.
check if key is not present in the array of keys to be removed then
Check if the value is object then call the function recursively
If its not object then add it to the result obj.
At last return the result object.
The code will convert the object of unknown depth to a plain object and you can also remove keys from nested objects.
const myObj = {
name: 'Luke',
age: 12,
height: '163cm',
weight: '60kg',
others: { one: '1', two: '2'}
};
const removed = ['height','weight','one'];
function removeKeys(obj,removed){
const res = {};
function helper(obj){
for(let key in obj){
if(!removed.includes(key)){
if(typeof obj[key] === "object"){
helper(obj[key]);
}
else res[key] = obj[key]
}
}
}
helper(obj)
return res;
}
const res = removeKeys(myObj,removed);
console.log(res)
I'm developing a React application where I need to convert a key-value object like this:
{
0: 'John',
1: 'Tim',
2: 'Matt'
};
To an array of just the values like this:
['John', 'Tim', 'Matt']
How do I accomplish this?
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = /* ??? */;
You could use Object.values.
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Object.values(object);
console.log(array);
With ES6, you could use Array.from and use a callback for the values.
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Array.from(Object.keys(object), k => object[k]);
console.log(array);
You can make use of Object.values command.
According to the docs.
Object.values() returns an array whose elements are the enumerable
property values found on the object. The ordering of the properties is
the same as that given by looping over the property values of the
object manually
Although it is an ES2017 solution but since you are using react, you can include stage-0 as a preset for babel and access this functionality
var data ={
0: 'John',
1: 'Tim',
2: 'Matt'
};
var newdata = Object.values(data);
console.log(newdata);
there are other methods like Object.keys which gives you all the keys as an array and Object.entries method returns an array of a given object's own enumerable property [key, value] pairs which might also be useful to you
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = [];
for(let key in obj){
arr.push(obj[key]);
}
While you have numerical keys and in an order without gaps, you could use Object.assign with an array as target and the given object as source.
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Object.assign([], object);
console.log(array);
This is commonly used one:
const obj={
1:'Azamat',
2: 'Kanybek',
3: 'Manas'}
console.log(Object.values(obj))
for key, value pairs:
const arr = [];
for(let key in obj){
arr.push([key,obj[key]])
}
console.log(arr)