简体   繁体   English

如何在 javascript/reactjs 中映射对象并分别使用其键和值

[英]how to map objects in javascript/ reactjs and use its key and values sepreately

i am trying to use data from an object that made by merging two arrays after making an object i am stuck at the part of how to map that object?我正在尝试使用来自一个对象的数据,该对象是在创建一个对象后合并两个数组而我被困在如何映射该对象的部分?

this is the javascript:-这是javascript:-

 class CampaignIndex extends Component { static async getInitialProps() { const campaigns = await factory.methods.getDeployedCampaigns().call(); //first array of dataset const data = await factory.methods.getDeployeddata().call(); //2nd array of dataset const sum = [ { description: data, location: campaigns, }, ]; var result = Object.assign.apply( {}, campaigns.map((v, i) => ({ [v]: data[i] })) );// merged them into one object console.log(result); // { // '0x0B1B7F35442bC8b122B612872e63860246Ae070F': 'this is a test', // '0xB8364AE9ce43D1136CbB74321302B3738b64452D': 'hope this works', // '0xD3E37a011d4c00109341D1de06659214e77c3695': 'hi' // } //console.log(data); //console.log(campaigns); return { campaigns, data, result, }; } renderCampaigns() { const { data, beta } = this.props; const items = result.map((term) => { return { header: term.key(), meta: term.values(), description: ( <Link as={`/campaigns/${term.values()}`} // href={{ // pathname: `/campaigns/show/`, // query: { address }, // }} > <a>view campaign</a> </Link> ), fluid: true, }; }); return <Card.Group items={items} />; }

the only way it kinda worked but not correctly the only way i know was by using two arrays but it showed all of the description in one single line cause i was only able to map the address它有点工作但不正确的唯一方法我知道的唯一方法是使用两个数组,但它在一行中显示了所有描述,因为我只能映射地址

 class CampaignIndex extends Component { static async getInitialProps() { const campaigns = await factory.methods.getDeployedCampaigns().call(); const data = await factory.methods.getDeployeddata().call(); const beta = data.map((description) => <h3>{description}</h3>); const sum = [ { description: data, location: campaigns, }, ]; console.log(data); console.log(campaigns); return { campaigns, data, beta, }; } renderCampaigns() { const { data, beta } = this.props; //const betas = data.map(description); const items = this.props.campaigns.map((address) => { return { header: data, meta: address, description: ( <Link as={`/campaigns/${address}`} href={{ pathname: `/campaigns/show/`, query: { address }, }} > <a>view campaign</a> </Link> ), fluid: true, }; }); return <Card.Group items={items} />;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

在此处输入图像描述

{ '0x0B1B7F35442bC8b122B612872e63860246Ae070F': 'this is a test', //the key is the address '0xB8364AE9ce43D1136CbB74321302B3738b64452D': 'hope this works', //the value is the description '0xD3E37a011d4c00109341D1de06659214e77c3695': 'hi' } { '0x0B1B7F35442bC8b122B612872e63860246Ae070F': 'this is a test', //the key is the address '0xB8364AE9ce43D1136CbB74321302B3738b64452D': 'hope this works', //the value is the description '0xD3E37a011d4c00109341D1de06659214e77c3695': 'hi' }

i want to render it in such a way that for every address it should create a new card group which i did from the code above but i could not insert the description in the same way cause if i map it out side the render it showed all the description in the same card unlike the addresses.我想以这样一种方式呈现它,即对于每个地址,它应该创建一个新的卡组,这是我从上面的代码中所做的,但我无法以相同的方式插入描述,因为如果我将它映射到它显示的所有渲染之外同一张卡中的描述与地址不同。 pls help!!请帮忙!!

There are a couple of ways to loop through an object's properties.有几种方法可以遍历对象的属性。 You can use a couple of methods: Object.keys() and Object.entries() are the most appropriate for your case.您可以使用几种方法: Object.keys()Object.entries()最适合您的情况。

  • Object.keys(obj) receives an object ( obj ) and returns an array of the object's keys . Object.keys(obj)接收一个对象( obj )并返回一个对象keys的数组。 This way you can do Object.keys(obj).map(key => { ... }) , you already have the key , and to get the value of it, you can simply do obj[key] .这样你就可以做Object.keys(obj).map(key => { ... }) ,你已经有了key ,要得到它的值,你可以简单地做obj[key]

  • Object.entries(obj) is very similar to Object.keys , but returns an array of arrays, each of these arrays is composed of the key and its value ( [key, value] ). Object.entries(obj)Object.keys非常相似,但返回一个数组数组,每个数组都由键及其值( [key, value] )组成。 So you can do Object.entries(entry => { ... }) , and to access the entry's key: entry[0] .所以你可以做Object.entries(entry => { ... }) ,并访问条目的键: entry[0] Same thing for the entry's value: entry[1] .条目的值也一样: entry[1]

Personally, I prefer to use Object.keys because it doesn't use the indexes to access the keys and values, but both should work.就个人而言,我更喜欢使用Object.keys ,因为它不使用索引来访问键和值,但两者都应该工作。

I believe your code would look like this:我相信您的代码将如下所示:

renderCampaigns() {
    const { data, beta } = this.props;

    const items = Object.keys(result).map((key) => {
      return {
        header: key,
        meta: result[key],
        description: (
          <Link
            as={`/campaigns/${result[key]}`}
            // href={{
            //   pathname: `/campaigns/show/`,
            //   query: { address },
            // }}
          >
            <a>view campaign</a>
          </Link>
        ),
        fluid: true,
      };
    });
    return <Card.Group items={items} />;
  }

First of all, provide you a quick answer but it's not a good one:首先,为您提供一个快速的答案,但这不是一个好的答案:

        const items = this.props.campaigns.map((address, index) => {
          return {
            header: data?.[index],
            meta: address,
            description: (
              <Link
                as={`/campaigns/${address}`}
                href={{
                  pathname: `/campaigns/show/`,
                  query: { address },
                }}
              >
                <a>view campaign</a>
              </Link>
            ),
            fluid: true,
          };
        });
        return <Card.Group items={items} />;

Bellow provides you with another refactor version for your reference. Bellow 为您提供了另一个重构版本供您参考。

It's always better to handle data first for better-maintaining purposes.为了更好的维护目的,首先处理数据总是更好的。

So if the order and indexing of 2 arrays are equal, you should ask API developers to combine data together in one single API.因此,如果 2 个数组的顺序和索引相同,您应该要求 API 开发人员将数据组合到一个 API 中。

If they're not able to do that, then we could use promise all to combine data together at the beginning.如果他们不能这样做,那么我们可以在一开始就使用 promise all 将数据组合在一起。

Let me use React hook to represent it since it's convenient to write and the performance is better.写起来方便,性能更好,我就用React hook来表示吧。


import React, { useEffect, useState } from 'react';
import Card from 'ooo'

function getCampaigns() {
    const getDeployedCampaignApiUrl = 'https://jsonplaceholder.typicode.com/todos/2'
    const getDeployedDataApiUrl = 'https://jsonplaceholder.typicode.com/todos/3'

    const urls = [getDeployedCampaignApiUrl,
        getDeployedDataApiUrl]
  
  return Promise.all(urls.map(url => fetch(url)
    .then(response => response.json())
    .then(responseBody => responseBody.list)))
    .then(lists => {
      const result =
        lists[0].map((item, i) => Object.assign({}, item, lists[1][i]));
    })
    .catch(err => {
      console.error('Failed to fetch one or more of these URLs:');
      console.error(err);
    });
}

function Campaign() {
  const [list, setList] = useState([]);

  useEffect(() => {
    let mounted = true;
    getCampaigns()
      .then(items => {
        if(mounted) {
          setList(items)
        }
      })
    return () => mounted = false;
  }, [])

  return (
        <>
       {list.map(item => <Card.Group key={item.id} item={Object.assign({}, item, {
           description: (
            <Link
                as={`/campaigns/${item.id}`}
                // href={{
                //   pathname: `/campaigns/show/`,
                //   query: { item.address },
                // }}
            >
                <a>{item.header}</a>
          </Link>
           )
       })} />)}
     </>  )
}

export default Compaign;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM