How to Find Object in a List of Items by Index Using Es6 (Reactjs)

Get the index of the object inside an array, matching a condition

As of 2016, you're supposed to use Array.findIndex (an ES2015/ES6 standard) for this:

a = [  {prop1:"abc",prop2:"qwe"},  {prop1:"bnmb",prop2:"yutu"},  {prop1:"zxvz",prop2:"qwrq"}];    index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);

How the ES6 map function creating array of object in JSX

This happens because you are mixing HTML (the th-tags) and JavaScript. Usually this is not possible in javascript as you realised. React uses an extended Syntax called JSX (details) that enables you to mix HTML and JS.

React automatically calls React.createElement on each of the JSX tags. This creates special objects (of the type React.element) that have all the typical properties a React object has (e.g. a key, ref, props etc.) (some more details). Usually this wanted behavior, e.g. if you re-use this.headerArr in a render function. For example render() return( <div>{this.headerArr}</div> )

In an array of objects, fastest way to find the index of an object whose attributes match a search

Maybe you would like to use higher-order functions such as "map".
Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

How do I update states `onChange` in an array of object in React Hooks

Here is how you do it:

// sample data structure
/* const data = [
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
] */ // make sure to set the default value in the useState call (I already fixed it)

const [data, setData] = useState([
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
]);

const updateFieldChanged = index => e => {
console.log('index: ' + index);
console.log('property name: '+ e.target.name);
let newArr = [...data]; // copying the old datas array
newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to

setData(newArr);
}

return (
<React.Fragment>
{data.map((datum, index) => {
<li key={datum.name}>
<input type="text" name="name" value={datum.name} onChange={updateFieldChanged(index)} />
</li>
})}
</React.Fragment>
)

How to render an array of objects in React?

You can do it in two ways:

First:

render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

return (
<div>
{listItems }
</div>
);
}

Second: Directly write the map function in the return

render() {
const data =[{"name":"test1"},{"name":"test2"}];
return (
<div>
{data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}

Check if item exists in array React

it should be:

handleCheck(val) {
return this.state.data.some(item => val.name === item.name);
}

because val here is an Object not a String.

Check this out:
https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q

How to find index of an object by key and value in an javascript array

The Functional Approach

All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for and each loops that have been proposed thus far and with ES6 syntax it is quite elegant.

Update

There's now a great way of doing this called findIndex which takes a function that return true/false based on whether the array element matches (as always, check for browser compatibility though).

var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});

With ES6 syntax you get to write this:

var index = peoples.findIndex(p => p.attr1 == "john");


The (Old) Functional Approach

TL;DR

If you're looking for index where peoples[index].attr1 == "john" use:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Explanation

Step 1

Use .map() to get an array of values given a particular key:

var values = object_array.map(function(o) { return o.your_key; });

The line above takes you from here:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

To here:

var values = [ "bob", "john", "larry" ];

Step 2

Now we just use .indexOf() to find the index of the key we want (which is, of course, also the index of the object we're looking for):

var index = values.indexOf(your_value);

Solution

We combine all of the above:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Or, if you prefer ES6 syntax:

var index = peoples.map((o) => o.attr1).indexOf("john");


Demo:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);

var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);

var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);

var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);

React, using .map with index

You need to to this:

todos.map((key, index) => { ... }) without object brackets for arguments.

({todo, index}) => { ... } - that syntax means that you want to get properties todo and index from first argument of function.

You can see syntax here:

Basic syntax

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }
singleParam => { statements }

// A function with no parameters requires parentheses:
() => { statements }

Advanced syntax

// Parenthesize the body to return an object literal expression:
params => ({foo: bar})

// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }

// Destructuring within the parameter list is also supported
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6

How to map an array of objects in React

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
{
name: 'Sam',
email: 'somewhere@gmail.com'
},

{
name: 'Ash',
email: 'something@gmail.com'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx



Related Topics



Leave a reply



Submit